Java 中的原始字符串-特别是正则表达式。多行字符串

在 Java 中有没有使用原始字符串的方法(没有转义序列) ?

(我正在编写大量的正则表达式代码和原始字符串,这将使我的代码更具可读性)

我理解这种语言并不直接提供这种功能,但是有没有任何方法可以以任何方式“模拟”它们呢?

47135 次浏览

No (quite sadly).

No, there isn't.

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

String#getBytes() exposes a copy of the internal byte array contained in every single String object which actually contains the 16-bit UTF-16 encoded String - the byte array will contain the same string converted to match the platform's default charset. What I'm saying is that I think this is as close to "raw" string as you can ever get in Java.

You could write your own, non-escaped property reader and put your strings in a resource file.

I personally consider regex strings data and not code, so I don't like them in my code--but I realize that's impractical and unpopular (Yes, I realize it, you don't have to yell at me).

Given that there is no native way to do this, I can come up with two possibilities (well, three but the third is, umm, unnatural).

So my personal preference would be to just parse a file into strings. You could name each entry in the file and load them all into a hash table for easy access from your code.

Second choice, create a file that will be pre-processed into a java interface; it could escape the regex as it does so. Personally I hate code generation, but if the java file is 100% never human edited, it's not too bad (the real evil is generated files that you are expected to edit!)

Third (tricky and probably a bad idea): You might be able to create a custom doclet that will extract strings from your comments into a text file or a header file at compile time, then use one of the other two methods above. This keeps your strings in the same file in which they are being used. This could be really hard to do correctly, and the penalties of failure are extreme, so I wouldn't even consider it unless I had an overwhelming need and some pretty impressive talent.

I only suggest this because comments are free-form and things within a "pre" tag are pretty safe from formatters and other system uglies. The doclet could extract this before printing the javadocs, and could even add some of the generated javadocs indicating your use of regex strings.

Before downvoting and telling me this is a stupid idea--I KNOW, I just thought I'd suggest it because it's interesting, but my preference as I stated above is a simple text file...

Have the raw text file in your class path and read it in with getResourceAsStream(....)

( Properties files are common, but messy - I treat most regex as code, and keep it where I can refer to it, and you should too. As for the actual question: )

Yes, there are ways to get around the poor readability. You might try:

String s = "crazy escaped garbage"; //readable version//

though this requires care when updating. Eclipse has an option that lets you paste text in between quotes, and the escape sequences are applied for you. The tactic would be to edit the readable versions first, and then delete the garbage, and paste them in between the empty quotes "".


Idea time:

Hack your editor to convert them; release as a plugin. I checked around for plugins, but found none (try searching though). There's a one-to-one correspondence between escaped source strings and textbox text (discounting \n, \r\n). Perhaps highlighted text with two quotes on the ends could be used.

String s = "##########
#####";

where # is any character, which is highlighted - the break is treated as a newline. Text typed or pasted within the highlighted area are escaped in the 'real' source, and displayed as if they were not. (In the same way that Eclipse escapes pasted text, this would escape typed text, and also display it without the backslashes.) Delete one of the quotes to cause a syntax error if you want to edit normally. Hmm.

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"

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.

No. But there's an IntelliJ plug-in that makes this easier to deal with, called String Manipulation.

IntelliJ will also automatically escape a string pasted into it. (As @Dread points out, Eclipse has a plug-in to enable this.)

Note : As of today, not available. Probably I'll edit this answer again whenever the feature release.

There is an ongoing proposal to introduce Raw Strings in Java. They actually much useful in the cases of regex.

Example 1: A regular expression string that was coded as

  System.out.println("this".matches("\\w\\w\\w\\w"));

may be alternately coded as

System.out.println("this".matches(`\w\w\w\w`));

since backslashes are not interpreted as having special meaning.

Example2 : A multi lines String literal with foreign language appends.

A multiple line string that was coded as
String html = "<html>\n" +
"    <body>\n" +
"         <p>Hello World.</p>\n" +
"    </body>\n" +
"</html>\n";

may be alternately coded as

 String html = `<html>
<body>
<p>Hello World.</p>
</body>
</html>
`;

which avoids the need for intermediate quotes, concatenation and explicit newlines.

Hopefully we can expect the release soon.

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.

The question asks for something akin to raw strings specifically to support Regular Expressions, which typically have portions akin to escape characters. So, for instance, \d means digit in regex and one would need to write \\d in a Java string. Meanwhile, a slash literal in regex would be written as \\ so in Java would be written as \\\\ which makes for difficult to read code.

The answer about proposed raw strings in Java was the most promising, but alas the proposal was not accepted. The answer about Pattern.quote() is good for certain strings, where there is overlap, but will not handle cases like \d and \w which are not valid Java strings in the first place. The answer about multiline strings will also not help with most of the complex regex strings which bothered the original questioner, who was looking for cleaner Java regex code.

My answer is therefore the following awkwardness. The backslash is known in Unicode as the Reverse Solidus. (The forward slash is the regular solidus.) Unicode has several alternatives which look like, especially in certain code editors (such as IntelliJ IDEA). These include the Big Reverse Solidus, Small Reverse Solidus, and Set Minus. Thus, channeling the Pattern.quote() answer, we write the regex using an alternative such as Big Reverse Solidus and perform string substitution for an escaped regular backslash when using it. The Big Reverse Solidus is unlikely to be needed for other aspects of your regex.

Thus, we can write:

Pattern pattern = Pattern.compile("∖d+".replace('∖', '\\'));

You might even write the string replacement into a static method similar to Pattern.quote() to get nicer looking code.