0

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); 
}
2
  • 1
    For syntax parsing, regex is not the best tool. It's likely to be feasible in your case, but very fragile. You should implement your own parser. Commented Oct 3, 2014 at 12:38
  • 1
    "I tried a few pattern," WHat did you try? And you're trying to count balanced parentheses which regexps are not suited to. As @Mena says, parse the strings some other way Commented Oct 3, 2014 at 12:38

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Avinash, this work. Thanks. I am also aware that this may not work if there is multiple space in between the commas?
then add \s* where the spaces are located. If you Still can't figure it out, then provide a sample string. I will try.
0

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'

1 Comment

However, I cannot strip the open/close brackets in the quote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.