Ziqi
Ziqi

Reputation: 2554

java regex escape all reserved characters

I understand that you can use Pattern.quote to escape characters within a string that is reserved by regex. But I do not understand why the following is not working:

String s="and this)";
String ps = "\\b("+Pattern.quote(s)+")\\b";
//String pp = Pattern.quote(pat);
Pattern p=Pattern.compile(ps);
Matcher mm = p.matcher("oh and this) is");

System.out.println(mm.find()); //print false, but expecting true?

When String s= "and this) is changed to String s="and this, i.e., no ), it works. How should I change the code so with ")" it also works as expected?

Thanks

Upvotes: 1

Views: 213

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

Use negative look-arounds to check for non-word characters before and after the keyword:

String ps = "(?<!\\w)"+Pattern.quote(s)+"(?!\\w)";

This way you will still match the s as a whole word and it won't be a problem is the keyword has non-word characters at the beginning or end.

IDEONE demo:

String s="and this)";
String ps = "(?<!\\w)"+Pattern.quote(s)+"(?!\\w)";
Pattern p=Pattern.compile(ps);
Matcher mm = p.matcher("oh and this) is");
System.out.println(mm.find()); 

Result: true

Upvotes: 2

Related Questions