groovy:如何替换所有';)';与'';

groovy:如何替换所有';)';与'';,groovy,replaceall,Groovy,Replaceall,我试过这个: def str1="good stuff 1)" def str2 = str1.replaceAll('\)',' ') 但我得到了以下错误: 异常org.codehaus.groovy.control.multipleCompositionErrorsException:启动失败,Script11.groovy:3:意外字符:'\'@第3行第29列。org.codehaus.groovy.control.ErrorCollector上有1个错误(failIfErrors:29

我试过这个:

def str1="good stuff 1)"
def str2 = str1.replaceAll('\)',' ')
但我得到了以下错误:

异常org.codehaus.groovy.control.multipleCompositionErrorsException:启动失败,Script11.groovy:3:意外字符:'\'@第3行第29列。org.codehaus.groovy.control.ErrorCollector上有1个错误(failIfErrors:296)

所以问题是我如何做到这一点:

str1.replaceAll('\)',' ')
与Java中相同:

def str2 = str1.replaceAll('\\)',' ')

您必须转义反斜杠(使用另一个反斜杠)。

您必须转义
\
内的
replaceAll

def str2 = str1.replaceAll('\\)',' ')

一种更常规的方式:
defstr2=str1.replaceAll(/\)/,”)
对于这个特定的例子,其他答案是正确的;但是,在实际情况下,例如,当使用
JsonSlurper
XmlSlurper
解析结果,然后替换其中的字符时,会出现以下异常:

groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.replaceAll() is applicable for argument types
考虑下面的例子

def result = new JsonSlurper().parseText(totalAddress.toURL().text)
例如,如果要用
'
替换
结果中的
(“
”等字符,下面将返回上述
异常

def subResult = result.replaceAll('\\(',' ')
这是因为Java中的
replaceAll
方法仅适用于
string
类型。为此,应将
toString()
添加到使用
def
定义的变量的结果中:

def subResult = result.toString().replaceAll('\\[',' ')