在Java中转义双引号

Vin*_*ent 55 java escaping

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

private static final String CREATE_TABLE_EXHIBITORS = "CREATE TABLE "users" ("_id" text PRIMARY KEY ,"name" text,"body" text,"image" text,"stand_id" text,"begin" long,"end" long,"changedate" long,"website" text,"facebook" text,"myspace" text,"twitter" text,"festivallink" text,"favorite" integer);";
Run Code Online (Sandbox Code Playgroud)

假设我希望此查询是Java中的有效字符串.我是否必须将其转换为在前面使用尾部斜线转义所有双引号?

e.g.  = "CREATE TABLE \"users"\
Run Code Online (Sandbox Code Playgroud)

或者是否有更快的方法使整个查询一次成为有效的字符串?我以为你可以在整个字符串周围使用单引号来做到这一点,但这也不起作用.

Sta*_*aro 54

使用Java replaceAll(String regex, String replacement)

例如,使用替换字符作为引号,然后将该char替换为 \"

String newstring = String.replaceAll("%","\"");
Run Code Online (Sandbox Code Playgroud)

或更换的所有实例\"\\\"

String newstring = String.replaceAll("\"","\\\"");
Run Code Online (Sandbox Code Playgroud)

  • `String.replaceAll("\"",Matcher.quoteReplacement("\\\""))` (10认同)

Ber*_*ase 45

使用反斜杠转义双引号是在Java中执行此操作的唯一方法.

诸如IntelliJ IDEA之类的一些IDE在将这样的字符串粘贴到字符串文字中时(即在围绕java字符串文字的双引号之间)自动转义

另一个选择是将String放入某种文本文件中,然后在运行时读取该文件