Why can't a regex in Java recognize \ s as a space character?

I read from a large number of web pages (for example: http://www.wellho.net/regex/java.html ), they all mentioned that \ s can represent any spatial character, But when I use \ s in Java, this is not a suitable expression.

Does anyone know the reason?

+3
source share
1 answer

To work, you need to quote backslashes inside strings.

For example, the following works just fine:

public class testprog {
    public static void main(String args[]) {
        String s = "Hello there";
        System.out.println (s.matches(".*\\s.*"));
    }
}

Conclusion:

true

If you use a type string "\s", you should receive an error message:

Invalid escape sequence - valid ones are  \b  \t  \n  \f  \r  \"  \'  \\

, \s escape- ( , ).

+10

Source: https://habr.com/ru/post/1760446/


All Articles