0

When I use the following code, it works:

String input = "8:32:03";
String filter = "(\\d{1,2}):(\\d{2})";
Pattern p = Pattern.compile(filter);
Matcher m = p.matcher(input);
if(m.find()) {  //Enters the condition.
    System.out.println("Found => " + m.group() );
}

However, when I try to take user input as regex it does not work?

String input = "8:32:03";
Scanner reader = new Scanner(System.in);
String filter = reader.nextLine();
Pattern p = Pattern.compile(filter);
Matcher m = p.matcher(input);
if(m.find()) {  //Does not enter the condition.
    System.out.println("Found => " + m.group() );
}

I tried using Pattern p = Pattern.compile(Pattern.quote(filter));
But that does not work either.
How can I take user input as a valid regex?

1
  • What is your input? Commented Sep 7, 2017 at 10:01

1 Answer 1

2

I am making an assumption here.. Are you inputting (\\d{1,2}):(\\d{2}) ?

If so, the \\ in your example act as escape for the \.. so for your input to be the same, you would need: (\d{1,2}):(\d{2})

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.