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?
Multiline Strings are now supported in Java via Text Blocks. In Java 13 and 14, this feature requires you to set the ––enable–preview option when building and running your project. In Java 15 and later, this option is no longer required as Text Blocks have become a standard feature.
If you want your string to span multiple lines, you have to concatenate multiple strings: String myString = "This is my string" + " which I want to be " + "on multiple lines."; It gets worse though. If you want your string to actually contain new lines, you need to insert \n after each line.
Why are raw strings often used when creating Regex objects? Raw strings are used so that backslashes do not have to be escaped.
Java 13 delivers long-awaited multiline strings. You no longer need to escape the special characters in string literals or use concatenation operators for values that span multiple lines. You can also control how to format your strings.
This is a work-around if you are using eclipse. You can automatically have long blocks of text correctly multilined and special characters automatically escaped when you paste text into a string literal
"-paste here-";
if you enable that option in window→preferences→java→Editor→Typing→"Escape text when pasting into a string literal"
No, there isn't.
Generally, you would put raw strings and regexes in a properties file, but those have some escape sequence requirements too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With