views:

258

answers:

4

i tried this:

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

but i got this:

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)

question: how to do this:

str1.replaceAll(')',' ')

A: 

Same as in Java:

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

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

Tomislav Nakic-Alfirevic
+2  A: 

You have to escape the \ inside the replaceAll

def str2 = str1.replaceAll('\\)',' ')
ccheneson
+3  A: 

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

John Stoneham
A: 

Many thanks to all answers which help me a lot as new learner of Groovy and Java!

Could you kindly tell me if we can use replaceAll() to replace more than one thing in one call. Like if I want to replace "(", "<","#" with "one", "two", "three"?

thank you again!

john