kinkajou kinkajou - 3 months ago 12
Java Question

How to capture multiple groups in regex?

I am trying to capture following word, number:

stxt:usa,city:14


I can capture usa and 14 using:

stxt:(.*?),city:(\d.*)$


However, when text is;

stxt:usa


The regex did not work. I tried to apply or condition using | but it did not work.

stxt:(.*?),|city:(\d.*)$

Answer

You may use

(stxt|city):([^,]+)

See the regex demo (note the \n added only for the sake of the demo, you do not need it in real life).

Pattern details:

  • (stxt|city) - either a stxt or city substrings (you may add \b before the ( to only match a whole word) (Group 1)
  • : - a colon
  • ([^,]+) - 1 or more characters other than a comma (Group 2).

Java demo:

String s = "stxt:usa,city:14";
Pattern pattern = Pattern.compile("(stxt|city):([^,]+)");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
}