groovy: how to replaceAll ')' with ' '
Asked Answered
B

5

34

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('\)',' ')
Beachcomber answered 11/4, 2010 at 13:34 Comment(0)
P
46

Same as in Java:

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

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

Polyhydroxy answered 11/4, 2010 at 13:38 Comment(1)
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.Sepalous
F
26

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

Forgiveness answered 11/4, 2010 at 15:26 Comment(0)
K
5

You have to escape the \ inside the replaceAll

def str2 = str1.replaceAll('\\)',' ')
Karelia answered 11/4, 2010 at 13:38 Comment(0)
F
4

just use method without regex:

def str2 = str1.replace(')',' ')
Flint answered 14/11, 2022 at 5:59 Comment(1)
This is the right way. Why create a regex if it's not necessary?Artillery
M
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('\\[',' ')
Mcginnis answered 26/2, 2017 at 9:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.