当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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'
分享给朋友:
您可能感兴趣的文章:
随机阅读: