1

i am trying to split the string using regex with closing bracket as a delimiter and have to keep the bracket..

i/p String: (GROUP=test1)(GROUP=test2)(GROUP=test3)(GROUP=test4)

needed o/p: 
(GROUP=test1)
(GROUP=test2)
(GROUP=test3)
(GROUP=test4)

I am using the java regex - "\([^)]*?\)" and it is throwing me the error..Below is the code I am using and when I try to get the group, its throwing the error..

    Pattern splitDelRegex = Pattern.compile("\\([^)]*?\\)");
    Matcher regexMatcher = splitDelRegex.matcher("(GROUP=test1)(GROUP=test2)    (GROUP=test3)(GROUP=test4)");
    List<String> matcherList = new ArrayList<String>();
    while(regexMatcher.find()){
        String perm = regexMatcher.group(1);
        matcherList.add(perm);
    }

any help is appreciated..Thanks

marc
  • 319
  • 1
  • 5
  • 20

4 Answers4

4

You simply forgot to put capturing parentheses around the entire regex. You are not capturing anything at all. Just change the regex to

Pattern splitDelRegex = Pattern.compile("(\\([^)]*?\\))");
                                         ^            ^  

I tested this in Eclipse and got your desired output.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
-1

You could use

str.split(")")

That would return an array of strings which you would know are lacking the closing parentheses and so could add them back in afterwards. Thats seems much easier and less error prone to me.

Encaitar
  • 398
  • 5
  • 16
-1

You could try changing this line :

String perm = regexMatcher.group(1);

To this :

String perm = regexMatcher.group();

So you read the last found group.

Winter
  • 3,894
  • 7
  • 24
  • 56
jambriz
  • 1,273
  • 1
  • 10
  • 25
-1

I'm not sure why you need to split the string at all. You can capture each of the bracketed groups with a regex.

Try this regex (\\([a-zA-Z0-9=]*\\)). I have a capturing group () that looks for text that starts with a literal \\(, contains [a-zA-Z0-9=] zero or many times * and ends with a literal \\). This is a pretty loose regex, you could tighten up the match if the text inside the brackets will be predictable.

String input = "(GROUP=test1)(GROUP=test2)(GROUP=test3)(GROUP=test4)";
String regex = "(\\([a-zA-Z0-9=]*\\))";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);

while(matcher.find()) { // find the next match
    System.out.println(matcher.group()); // print the match
}

Output:

(GROUP=test1)
(GROUP=test2)
(GROUP=test3)
(GROUP=test4)
Matt
  • 3,677
  • 1
  • 14
  • 24