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?!
} else if (input.matches("A=(\\w+)")) { output="value of key A is " + input.split("=")[1]; }Patternand 1Matcherbyiftest. But if you know how to use it, I'm not sure to get the question ? Note that creatingPatterncould be costly so avoid to create it at each call (baeldung.com/java-regex-pre-compile). By the way, maybe this is just a simple example to illustrate but in your simple case using regexep seems overkill.input.startsWith("#")is a lot faster than input.matches("#.*"). Regular expressions are not the solution to every problem.