Question

I tried this:

def str1="good stuff 1)"
def str2 = str1.replaceAll('\)',' ')

but i got the following error:

Exception org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed, Script11.groovy: 3: unexpected char: '\' @ line 3, column 29. 1 error at org.codehaus.groovy.control.ErrorCollector(failIfErrors:296)

so the question is how do I do this:

str1.replaceAll('\)',' ')
Was it helpful?

Solution

Same as in Java:

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

You have to escape the backslash (with another backslash).

OTHER TIPS

A more Groovy way: def str2 = str1.replaceAll(/\)/,' ')

You have to escape the \ inside the replaceAll

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

The other answers are correct for this specific example; however, in real cases, for instance when parsing a result using JsonSlurper or XmlSlurper and then replacing a character in it, the following Exception occurs:

groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.replaceAll() is applicable for argument types

Consider the following example,

def result = new JsonSlurper().parseText(totalAddress.toURL().text)

If one wants to replace a character such as '(' in result with a ' ' for example, the following returns the above Exception:

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

This is due to the fact that the replaceAll method from Java works only for string types. For this to work, toString() should be added to the result of a variable defined using def:

def subResult = result.toString().replaceAll('\\[',' ')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top