【问题标题】:How do I find and replace all escaped quotes and regular quotes with different values?如何使用不同的值查找和替换所有转义引号和常规引号?
【发布时间】:2020-06-19 04:17:29
【问题描述】:

我希望将字符串中出现的所有转义引号 (\") 替换为 (\\\"),然后将所有剩余的未转义引号 (") 替换为转义引号 (\")。到目前为止,这是我尝试过的:

row = row.replaceAll("\\\\(?>\")", "\\\\\"");
row = row.replaceAll("((?<!\\\\)\")", "\"");

示例输入: "This is a test with \" and "'s where \" is replaced with triple \'s before "

示例输出:\"This is a test with \\\" and \"'s where \\\" is replaced with triple \'s before \"

\\(?&gt;\")"https://www.freeformatter.com/java-regex-tester.html#ad-output 上工作,在 replaceAll 中找不到转义引号。

对此的任何帮助表示赞赏。

【问题讨论】:

  • @Mandy8055 不,它捕获了所有的 \,而不仅仅是那些前缀引号的。所以“This is a test with \ and \” ...”都被替换了。

标签: java regex


【解决方案1】:

看起来你需要四个 \'s 才能找到一个 .我使用了回溯和向前查找“\”。感谢java, regular expression, need to escape backslash in regex

"\\\\(?&gt;\")" 会找到\"。

"(?&lt;!\\\\)\"" 会找到前面没有 \ 的 "。

所以我找到的解决方案是:

        Pattern escapePattern = Pattern.compile("\\\\(?>\")");
        Pattern quotePattern = Pattern.compile("(?<!\\\\)\"");

        for(String row : rows.split("\n")) {
            Matcher escapeMatcher = escapePattern.matcher(row.trim());
            String escapedString = escapeMatcher.replaceAll("\\\\\\\\\\\\\"");

            Matcher quoteMatcher = quotePattern.matcher(escapedString);
            queryRows.add(quoteMatcher.replaceAll("\\\\\""));
        }

【讨论】:

    【解决方案2】:

    只需将单个反斜杠替换为三个反斜杠,然后将引号替换为反斜杠引号:

    row = row.replaceAll("\\\\(?!')", "\\\\\\\\\\\\").replace("\"", "\\\"");
    

    【讨论】:

    • 这不会与单独的\'s一起工作吧? IE。 "test \ \"" 将返回 "test \\ \\\"" rgiht?
    【解决方案3】:

    先将单个 (\) 替换为 (\\),然后将 (") 替换为 (\")

    row = row.replace("\\", "\\\\").replace("\"", "\\\"");
    

    【讨论】:

      猜你喜欢
      • 2013-09-24
      • 2012-07-07
      • 2013-02-24
      • 2011-05-11
      • 2013-01-22
      • 2012-01-01
      • 1970-01-01
      • 2013-04-15
      • 2017-08-05
      相关资源
      最近更新 更多