如何查找并用不同的值替换所有转义的引号和常规引号?

时间:2020-06-19 04:17:29

标签: java regex

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

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 \"

\\(?>\")"在replaceAll中的https://www.freeformatter.com/java-regex-tester.html#ad-output上有效,找不到转义的引号。

对此有任何帮助。

3 个答案:

答案 0 :(得分:0)

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

semantic-ui-react

答案 1 :(得分:0)

您似乎需要四个\来找到一个。我进行了回顾,并期待找到\“。感谢java, regular expression, need to escape backslash in regex

"\\\\(?>\")"将找到\“。

"(?<!\\\\)\""会在其前面找到不带\的“。”

所以我发现这两种方法都是:

        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 :(得分:0)

首先用(\\)替换单个(\),然后将(“)替换为(\”)

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