在 Java 中,有没有办法编写字符串文字而不必转义引号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3034186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:49:42  来源:igfitidea点击:

In Java, is there a way to write a string literal without having to escape quotes?

javastringescaping

提问by Matthew

Say you have a String literal with a lot of quotation marks inside it. You could escape them all, but it's a pain, and difficult to read.

假设你有一个字符串文字,里面有很多引号。你可以避开它们,但这很痛苦,而且难以阅读。

In some languages, you can just do this:

在某些语言中,您可以这样做:

foo = '"Hello, World"';

In Java, however, ''is used for chars, so you can't use it for Strings this way. Some languages have syntax to work around this. For example, in python, you can do this:

但是,在 Java 中,''用于chars,因此您不能以String这种方式将其用于s。某些语言具有解决此问题的语法。例如,在 python 中,你可以这样做:

"""A pretty "convenient" string"""

Does Java have anything similar?

Java有没有类似的?

采纳答案by Hyman

The answer is no, and the proof resides in the Java Language Specification:

答案是否定的,证据在Java 语言规范中

  StringLiteral:
   "StringCharacters"

  StringCharacters:
   StringCharacter
   | StringCharacters StringCharacter

  StringCharacter:
   InputCharacter but not " or \
   | EscapeSequence

As you can see a StringLiteralcan just be bound by "and cannot contain special character without escapes..

如您所见, aStringLiteral只能被绑定"并且不能包含没有转义的特殊字符。

A side note: you can embed Groovyinside your project, this will extend the syntax of Java allowing you to use '''multi line string ''', ' "string with single quotes" 'and also "string with ${variable}".

旁注:您可以将Groovy嵌入到您的项目中,这将扩展 Java 的语法,允许您使用'''multi line string ''',' "string with single quotes" '"string with ${variable}".

回答by Chris Lercher

Simple answer: No.

简单的回答:不。

For longer strings that must be escaped, I usually read them from some external resource.

对于必须转义的较长字符串,我通常从一些外部资源中读取它们。

回答by benjismith

No, and I've always been annoyed by the lack of different string-literal syntaxes in Java.

不,我一直对 Java 中缺少不同的字符串文字语法感到恼火。

Here's a trick I've used from time to time:

这是我不时使用的一个技巧:

String myString = "using `backticks` instead of quotes".replace('`', '"');

I mainly only do something like that for a static field. Since it's static the string-replace code gets called once, upon initialization of the class. So the runtime performance penalty is practically nonexistent, and it makes the code considerably more legible.

我主要只为静态字段做类似的事情。由于它是静态的,字符串替换代码在类初始化时被调用一次。所以运行时性能损失实际上是不存在的,它使代码更加清晰。

回答by Doua Beri

you can also use StringEscapeUtilsfrom apache commons

您还可以使用apache commons 中的StringEscapeUtils

UPDATE: If someone is interested in some examples here is a useful link : http://java.dzone.com/articles/commons-lang-3-improved-and-powerful-StringEscapeUtils

更新:如果有人对这里的一些例子感兴趣,这里有一个有用的链接:http: //java.dzone.com/articles/commons-lang-3-improved-and-powerful-StringEscapeUtils

回答by SreejithVS

If you want to escape 'or "in your string, you can use the following code:

如果要转义'"在字符串中,可以使用以下代码:

String text = ...

text = text.replaceAll("('|\")", "\\");

回答by Anonymous Person

The following seems to work for me:

以下似乎对我有用:

String x = "Some Text" + '"' + "More Text" + '"' + "Even More Text";

I think because char is the primitive variable type for String, Strings and chars can be combined (at least the eclipse compiler doesn't seem to complain).

我认为因为 char 是 String 的原始变量类型,所以 Strings 和 chars 可以组合(至少 eclipse 编译器似乎没有抱怨)。

回答by VonC

Update Dec. 2018 (12 months later):

2018 年 12 月更新(12 个月后):

Raw string literals (which are on the amber list) won't make it to JDK 12.
See the criticisms here.

原始字符串文字(位于琥珀色列表中)不会出现在 JDK 12 中。
请参阅此处批评



There might be in a future version of Java (10 or more).

可能会有 Java 的未来版本(10 个或更多)。

See JEPS 8196004from January 2018: ("JEP" is the "JDK Enhancement Program")

请参阅2018 年 1 月的JEPS 8196004:(“JEP”是“JDK 增强程序”

JEP draft: Raw String Literals

Add a new kind of literal, a raw string literal, to the Java programming language.
Like the traditional string literal, a raw string literal produces a String, but does not interpret string escapes and can span multiple lines of source code.

JEP 草案:原始字符串文字

向 Java 编程语言添加一种新的文字,原始字符串文字。
与传统的字符串文字一样,原始字符串文字会生成一个字符串,但不会解释字符串转义,并且可以跨越多行源代码

So instead of:

所以而不是:

Runtime.getRuntime().exec("\"C:\Program Files\foo\" bar");
String html = "<html>\n"
              "    <body>\n" +
              "         <p>Hello World.</p>\n" +
              "    </body>\n" +
              "</html>\n";
System.out.println("this".matches("\w\w\w\w"));

You would be able to type:

你可以输入:

Runtime.getRuntime().exec(`"C:\Program Files\foo" bar"`);

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

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

Neat!

整洁的!

But it is still just a draft: it will need to posted, submitted, be a candidate, and funded, before being completed and making it into the next JDK.

但它仍然只是一个草案:在完成并进入下一个 JDK 之前,它需要发布、提交、成为候选人和资助。