Version difference? Regex Escape in Java

Viewed 120

It seems that the regex escaping works different in different versions of Java.

  1. In Java openjdk 16.0.1 the compilation works fine

  2. In Java openjdk 11.0.11 this compilation error is thrown:

test.java:15: error: illegal escape character
        if (variable.matches("\s*")){

I know, that I'm generally on the safe side with \\. My question:

Since which version changed this behavior? And why works this?

2 Answers

The behavior that caught your attention was introduced with the new feature of TextBlocks

This new feature was first introduced in Java 13 and the specific change which is the reason for the behavior that you observe, came with the second preview of TextBlocks which was included in Java 14 Text Blocks Second Preview .

According to Text Blocks Second Preview

the new \s escape sequence simply translates to a single space (\u0020).

The \s escape sequence can be used in both text blocks and traditional string literals.

Also this new feature about TextBlocks was officially included in LTS version of Java 17.

Java 15 introduced \s as a valid escape sequence meaning "space" (unicode 0x20) in the language standard.

Non-valid escape sequences generate a compile-time error (that's also in the link above). Since before Java 15 that escape sequence wasn't valid, it threw an error. From Java 15 onward it's a valid escape sequence.

Related