CoderX
CoderX

Reputation: 1022

User Input as regex not working in JAVA

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?

Upvotes: 0

Views: 123

Answers (1)

Arcturus
Arcturus

Reputation: 27055

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

Upvotes: 2

Related Questions