Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regexto match tuples

I need to extract tuples out of string

e.g. (1,1,A)(2,1,B)(1,1,C)(1,1,D)

and thought some regex like:

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

would work but it just gives me the first tuple. What would be proper regex to match all the tuples in the strings.

like image 808
Vihaan Verma Avatar asked Feb 13 '23 08:02

Vihaan Verma


1 Answers

Remove the * from the regex and iterate over the matches using a 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());
}

The * character is a quantifier that matches zero or more tuples. Hence your original regex would match the entire input string.

like image 53
M A Avatar answered Feb 14 '23 22:02

M A