Home > Software design >  Version difference? Regex Escape in Java
Version difference? Regex Escape in Java

Time:12-13

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?

CodePudding user response:

This is the feature that brought the change you found out.

Java TextBlock feature.

It was introduced in Java 13 and that change came with the second preview 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.

This new feature about TextBlocks was also officialy included in LTS version of Java 17.

CodePudding user response:

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