Home > Enterprise >  Regex capture group within if statement in Java
Regex capture group within if statement in Java

Time:07-05

I'm facing a stupid problem... I know how to use Pattern and Matcher objects to capture a group in Java.

However, I cannot find a way to use them with an if statement where each choice depends on a match (simple example to illustrate the question, in reality, it's more complicated) :

String input="A=B";
String output="";

if (input.matches("#.*")) {
    output="comment";
} else if (input.matches("A=(\\w )")) {
    output="value of key A is ..."; //how to get the content of capturing group?
} else { 
    output="unknown";
}

Should I create a Matcher for each possible test?!

CodePudding user response:

Yes, you should.

Here is the example.

Pattern p = Pattern.compile("Phone: (\\d{9})");
String str = "Phone: 123456789";
Matcher m = p.matcher(str);
if (m.find()) {
    String g = m.group(1); // g should hold 123456789
}
  • Related