Smith Thapa Smith Thapa - 18 days ago 5
Java Question

Regex: What do i need to do if i want to find "\" and "s" in a given pattern?

I know \s helps to find whitespace character but what do i need to to find "\" and "s" in a given string ?


Pattern p = Pattern.compile("[s\]");


Pattern p = Pattern.compile("[\s]");

gives illegal escape character error .


You need to escape the \ again, to be parsed as a literal backslash character:

Pattern p = Pattern.compile("[s\\\\]");

Note that I used \\\\ instead of just \\ because, \\s would actually translate to \s in the pattern, which will look for white-space characters.

You can also read about this behaviour here.

Based on your recent comment, you do not need the character set either.

Pattern p = Pattern.compile("\\\\s");