Search code examples
javaregexif-statementcapturing-group

Regex capture group within if statement in Java


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?!


Solution

  • 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
    }