gpt4 book ai didi

regex - 从 Groovy 表达式内部双重转义正则表达式

转载 作者:行者123 更新时间:2023-12-02 04:49:59 29 4
gpt4 key购买 nike

注意:我不得不简化我的实际用例以节省大量背景故事。因此,如果您对这个问题的第一 react 是:您为什么要这样做,请相信我,我只是需要这样做。

我正在尝试编写一个 Groovy 表达式,用单引号 ("'") 替换出现在字符串中的双引号 (""") .

// BEFORE: Replace my "double" quotes with 'single' quotes.
String toReplace = "Replace my \"double-quotes\" with 'single' quotes.";

// Wrong: compiler error
String replacerExpression = "toReplace.replace(""", "'");";

Binding binding = new Binding();
binding.setVariable("toReplace", toReplace);
GroovyShell shell = new GroovyShell(binding);

// AFTER: Replace my 'double' quotes with 'single' quotes.
String replacedString = (String)shell.evaluate(replacerExpression);

问题是,我在分配 replacerExpression 的那一行遇到编译错误:

Syntax error on token ""toReplace.replace("", { expected

我认为这是因为我需要对包含双引号字符 (""") 的字符串进行转义,但由于它是一个字符串中的字符串,所以我不确定如何在此处正确地对它进行转义。任何想法?

最佳答案

您需要在该行的引号内转义引号:

String replacerExpression = "toReplace.replace(""", "'");";

字符串将被评估两次:一次作为字符串文字,一次作为脚本。这意味着你必须用反斜杠转义它,并且也要转义反斜杠。此外,对于嵌入式引号,如果您使用三重引号,它的可读性会更高。

试试这个(常规方式):

String replacerExpression = """toReplace.replace("\\"", "'");""";

在 Java 中,您不得不使用反斜杠来转义所有引号和嵌入的反斜杠:

String replacerExpression = "toReplace.replace(\"\\\"\", \"\'\");";

关于regex - 从 Groovy 表达式内部双重转义正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19037031/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com