Home > Enterprise >  Java regex inside text blocks
Java regex inside text blocks

Time:09-08

I surely hoped that this would be supported:

private static void regex() {
    String plain = "\\w ";
    String withTextBlocks = """
        \w 
    """;
}

but withTextBlocks does not compile under Java-17. Isn’t it the point of text blocks that we should not escape? I have been through the JEP and maybe the explanation is there, but I can't grok through it. And a second question in case someone knows, is there a future JEP for this? Thank you.

PS It works in Kotlin.

CodePudding user response:

You are conflating text blocks with raw strings. These are different features, though they were explored together and this may explain why you mentally folded them together. There is no support yet for raw strings (which turn out to be somewhat more slippery than they might first appear.)

Isn’t it the point of text blocks that we should not escape?

No, that is not the point of text blocks. The point of text blocks is to allow us to represent two dimensional blocks of text in code, preserving the block's relative indentation but not absolute indentation. This allows us to freely indent the source representation of the text block itself to match surrounding code, without affecting the indentation of the string the text block describes.

An additional design goal is that text blocks should differ from ordinary string literals only in ways that pertain to their two-dimensional nature. There should not be a different set of escape characters, or different escaping rules. (If we ever do raw strings, it should apply equally to text blocks and traditional string literals.) If text blocks worked the way you wanted, you'd probably be complaining that you can't do the same with single-line strings. These aspects are orthogonal and the language should treat them orthogonally.

  • Related