Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 404
Debajit Avatar asked Aug 10 '09 19:08

Debajit


People also ask

How do you handle a multiline string in Java?

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.

How do you assign a multiline string in Java?

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 do raw strings often appear in regex objects?

Why are raw strings often used when creating Regex objects? Raw strings are used so that backslashes do not have to be escaped.

Does Java support multiline strings?

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.


2 Answers

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"

like image 52
Dread Avatar answered Sep 19 '22 16:09

Dread


No, there isn't.

Generally, you would put raw strings and regexes in a properties file, but those have some escape sequence requirements too.

like image 25
stevedbrown Avatar answered Sep 19 '22 16:09

stevedbrown