scottm
scottm

Reputation: 28699

Regex to match anything between parenthesis

I'm using regex to replace a specific pattern with a more simple one.

I need to take all characters, white space, from between two parentheses and use them in a capture group. However, it is possible for the characters between the parentheses are also parentheses.

Here are two examples of what I am trying to match:

.message("vel pharetra est urna eget justo. Nunc in dignissim velit. {} "
        + error.getMessage().getProperty())
.build().log();   

.message("Key : " + oldEntry.getKey() + " and Value: " + oldEntry.getValue())
    .build()
    .log();

My current regex: \.message\(([\S\s]+?)\)[\S\s]*?((\.log\(\))|(\.build\(\)))\;

It matches simple patterns when there are not parentheses in the message. But when there are parentheses, it stops the capture group at the first closing parenthesis. I'm sure this is because I'm using +? but I'm not sure how to specify that the search should continue.

I've created this regexr with a few examples. http://regexr.com/3h15u

Upvotes: 2

Views: 337

Answers (1)

anubhava
anubhava

Reputation: 786349

You may use this regex:

\.message\((?s)(.+?)\)\s*(?:\.(?:log|build)\(\)\s*)+\s*;

Text between ( and ) is being captured in captured group #1

RegEx Demo

In Java use:

final String regex = "\\.message\\((?s)(.+?)\\)\\s*(?:\\.(?:log|build)\\(\\)\\s*)+\\s*;";

Upvotes: 5

Related Questions