0

My regex matcher is returning false, and I can't understand why. It works fine on regexr.com

Here's the code:

        String test = "Calm_fit calm://listpage?pageid=fitnesstab SomeText";
        Pattern pattern = Pattern.compile("/\bcalm?:\/\/\S+/gi");
        Matcher matcher = pattern.matcher(test);
        System.out.println("Here 1");

        if (matcher.find()) {
            System.out.println("Here 2 Matched: " + matcher.group(1));
        }

Here 2 Matched: is not getting printed. Control doesn't enter if statement. I'm trying to extract the url calm://listpage?pageid=fitnesstab from the text.

Am I missing something here ? Thanks in advance!

1 Answers1

-1

To summarize:

  • Java regular expressions are defined as strings, not as regex literals. This means that
    • You don't need to delimit your expression using forward slashes.
    • Backslashes need to be escaped.
    • Literal forward slashes don't need to be escaped.
  • Flags like Pattern.CASE_INSENSITIVE can be passed as an argument to the Pattern.compile() method.
  • Your expression has no group 1. Either use group 0 or add additional parentheses to define a group.

Putting it all together:

import java.util.regex.*;

public class MyClass {
    public static void main(String args[]) {
        String test = "Calm_fit calm://listpage?pageid=fitnesstab SomeText";
        Pattern pattern = Pattern.compile("\\bcalm?://\\S+",
                Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(test);

        if (matcher.find()) {
            System.out.println(matcher.group(0));
        }
    }
}

This produces the following output:

calm://listpage?pageid=fitnesstab
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156