0

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

5
  • } else if (input.matches("A=(\\w+)")) { output="value of key A is " + input.split("=")[1]; } Commented Jul 1, 2022 at 16:27
  • 1
    If you really want to use regexep you should probably use 1 Pattern and 1 Matcher by if test. But if you know how to use it, I'm not sure to get the question ? Note that creating Pattern could 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. Commented Jul 1, 2022 at 16:32
  • input.startsWith("#") is a lot faster than input.matches("#.*"). Regular expressions are not the solution to every problem. Commented Jul 1, 2022 at 17:12
  • It is a simple example: the real problem is of course more complicated :) Commented Jul 4, 2022 at 12:55
  • @sbernard: the question was exactly that. In fact, I started using regex in Perl. And in Perl, it's very simple to code (no need to have as many objects as if statements). I found it strange to need as many Pattern/Matcher pairs as if statements and wanted to get advice thank you :) ! And yes, the real example is far more complicated. Commented Jul 4, 2022 at 13:05

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.