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

Solution 1:

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"

Solution 2:

No, there isn't.

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

Solution 3:

I use Pattern.quote. And it solves the problem of the question. Thusly:

Pattern pattern = Pattern.compile(Pattern.quote("\r\n?|\n"));

The quote method returns a string that would match the provided string argument, which the return string is the properly quoted string for our case.

Solution 4:

No (quite sadly).