Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy: how to replaceAll ')' with ' '

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('\)',' ') 
like image 263
john Avatar asked Apr 11 '10 13:04

john


People also ask

How do I remove characters from a string in Groovy?

Groovy has added the minus() method to the String class. And because the minus() method is used by the - operator we can remove parts of a String with this operator. The argument can be a String or a regular expression Pattern. The first occurrence of the String or Pattern is then removed from the original String.

What do the replaceAll () do?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement .


2 Answers

Same as in Java:

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

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

like image 127
Tomislav Nakic-Alfirevic Avatar answered Sep 28 '22 06:09

Tomislav Nakic-Alfirevic


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

like image 22
John Stoneham Avatar answered Sep 28 '22 05:09

John Stoneham