kinkajou kinkajou - 1 year ago 70
Java Question

How to capture multiple groups in regex?

I am trying to capture following word, number:


I can capture usa and 14 using:


However, when text is;


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


Answer Source

You may use


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()){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download