简体   繁体   中英

Regex getting String in between parenthesis

I am just learning about using Regex and it does seem a bit complicated to me.

I am trying to parse this String in Java:

new Array(new Array('1','Hello'),new Array('2','World (New) Again'),new Array('3','Now'));

I want the output to end up as these matches:

'1','Hello'
'2','World (New) Again'
'3','Now'

I tried a few pattern, but the best I can get is that I get:

'1','Hello'
'2','World (New
) Again'
'3','Now'

This is my code:

Pattern pattern2 = Pattern.compile("([^\\(]*[']*['][^\\)]*[']*)");
s = "new Array(new Array('1','Hello'),new Array('2','World (New) Again'),new Array('3','Now'));";
Matcher matcher = pattern2.matcher(s);

while(matcher.find()){
    String match = matcher.group(1);
    System.out.println(match); 
}

The below code will work if the json string format is like the above.

String s = "new Array(new Array('1','Hello'),new Array('2','World (New) Again'),new Array('3','Now'));";
Pattern regex = Pattern.compile("[(,]new\\sArray\\(((?:(?!\\),new\\sArray|\\)+;).)*)\\)");
 Matcher matcher = regex.matcher(s);
 while(matcher.find()){
        System.out.println(matcher.group(1));
 }

Output:

'1','Hello'
'2','World (New) Again'
'3','Now'

DEMO

You need to split making sure there are no close brackets between the close/open pairs:

You can do the whole thing in one line:

String[] parts = str.replaceAll("^(new Array\\()*|\\)*;$", "").split("\\)[^)]*?Array\\(");

Some test code:

String str = "new Array(new Array('1','Hello'),new Array('2','World (New) Again'),new Array('3','Now'));";
String[] parts = str.replaceAll("^(new Array\\()*|\\)*;$", "").split("\\)[^)]*?Array\\(");
for (String part : parts)
    System.out.println(part);

Output:

'1','Hello'
'2','World (New) Again'
'3','Now'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM