javaregexstringrawstring

Raw Strings in Java - for regex in particular. Multiline strings


Is there any way to use raw strings in Java (without escape sequences)?

(I'm writing a fair amount of regex code and raw strings would make my code immensely more readable)

I understand that the language does not provide this directly, but is there any way to "simulate" them in any way whatsoever?


Solution

  • Yes.

    Text Blocks Come to Java

    Java 13 delivers long-awaited multiline strings

    Some history: Raw String Literals were withdrawn. This was intended to be a preview language feature in JDK 12, but it was withdrawn and did not appear in JDK 12. It was superseded by Text Blocks (JEP 355) in JDK 13.

    You can use text blocks to define multiline String literals with ease. You don’t need to add the visual clutter that comes with regular String literals: concatenation operators and escape sequences. You can also control how the String values are formatted. For example, let’s look at the following HTML snippet:

    String html = """
    <HTML>
      <BODY>
        <H1>"Java 13 is here!"</H1>
      </BODY>
    </HTML>""";
    

    Notice the three quotation marks that delimit the beginning and ending of the block.