31

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('\)',' ')
Daniel A.A. Pelsmaeker
  • 47,471
  • 20
  • 111
  • 157
john
  • 2,572
  • 11
  • 35
  • 51

5 Answers5

43

Same as in Java:

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

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

Tomislav Nakic-Alfirevic
  • 10,017
  • 5
  • 38
  • 51
  • As pointed out in another answer, in both Java and Groovy you should not use a RegEx at all and use `.replace()` instead. That solution is much faster and you don't need to care about escaping the closing bracket. – winne2 Jul 19 '23 at 11:47
26

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

John Stoneham
  • 2,485
  • 19
  • 10
5

You have to escape the \ inside the replaceAll

def str2 = str1.replaceAll('\\)',' ')
ccheneson
  • 49,072
  • 8
  • 63
  • 68
2

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('\\[',' ')
Ali Nem
  • 5,252
  • 1
  • 42
  • 41
2

just use method without regex:

def str2 = str1.replace(')',' ')
Serge
  • 21
  • 1