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('\\[',' ')