Smith Thapa Smith Thapa - 2 months ago 9
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 ?

BOTH:

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


and,

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


gives illegal escape character error .

Answer

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");