Java regexto matches tuples

I need to extract tuples from a string

eg. (1,1,A)(2,1,B)(1,1,C)(1,1,D)

and thought of some kind of regular expression:

String tupleRegex = "(\\(\\d,\\d,\\w\\))*";

will work, but it just gives me the first tuple. What will be the correct regular expression to match all tuples in strings.

+4
source share
2 answers

Extract *from the regex and swipe through them with java.util.regex.Matcher:

String input = "(1,1,A)(2,1,B)(1,1,C)(1,1,D)";
String tupleRegex = "(\\(\\d,\\d,\\w\\))";
Pattern pattern = Pattern.compile(tupleRegex);
Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
    System.out.println(matcher.group());
}

A symbol *is a quantifier that matches zero or more tuples. Therefore, your original regular expression will match the entire input string.

+6
source

String.split() (?!^\\()(?=\\()

Arrays.toString("(1,1,A)(2,1,B)(1,1,C)(1,1,D)".split("(?!^\\()(?=\\()"))

:

[(1,1,A), (2,1,B), (1,1,C), (1,1,D)]

DEMO.

:

  (?!                      look ahead to see if there is not:
    ^                        the beginning of the string
    \(                       '('
  )                        end of look-ahead
  (?=                      look ahead to see if there is:
    \(                       '('
  )                        end of look-ahead
+2

All Articles