简体   繁体   English

用(\\“)替换(”)的正则表达式?

[英]Regular expression to replace (“) with (\”)?

Why does the following not work: 为什么以下方法不起作用:

      String test = "hello\"world".replaceAll("\"", "\\\"");
      System.out.println(test);

What I'm trying to do is replace any occurrence of " with \\" . 我想做的是将任何出现的"替换为\\"

So I want to get as output: 所以我想作为输出:

hello\"world

Regular expressions are overkill for this. 正则表达式对此过于矫kill过正。

myString.replace("\"", "\\\"")

should do just fine and is more readable to someone familiar with the core libraries. 应该做得很好,并且对于熟悉核心库的人来说更具可读性。

The replace method just replaces one substring with another. replace方法只是将一个子字符串替换为另一个子字符串。

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. 用指定的文字替换序列替换此字符串中与文字目标序列匹配的每个子字符串。 The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab" . 替换从字符串的开头到结尾进行,例如,在字符串"aaa"中将"aa"替换为"b" "aaa"将得到"ba"而不是"ab"

String test = "hello\"world".replaceAll("\"", "\\\\\"");
System.out.println(test);

You need to two more \\\\ to escape the escape character, for a total of 5 \\ s. 您还需要两个\\\\来转义转义字符,总共需要5 \\ s。

\\\\ - escape the escape character \\\\ -转义转义字符

\\\\ - to display the character \\\\ -显示字符

\\ - to escape the quote. \\ -转义报价。

Try: 尝试:

String test = "hello\"world".replaceAll("\"", "\\\\\"");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM