javastringgroovychargroovyscriptengine

Groovy string parsing by ignoring "$" or any character(ps: no control over input data)


I am trying to replace a particular word say password to ******* from a string which has characters such as $ and \n in Groovy.

I cannot escape them by using \ because i have no control over data i receive and even in the final output i need as it was earlier with $.

i tried str.replaceAll("password","**")

gives:

illegal string body character after dollar sign; solution: either escape a literal dollar sign "\$5" or bracket the value expression "${5}" @ line 2, column 8. afdmas$

def str="""hello how  
you$
password
doing"""

expected o/p :

hello how  
you$
**
doing

Solution

  • It's not clear why you don't have access to the input data because you use string literal in the example and the error you get is from this example as well. In this case you can use Groovy single-quoted strings but they are without interpolation. Or if interpolation is necessary then you can use slashy or dollar slashy strings which additionally don't require backslash escaping:

    def str='''"hello how
    you$ password doing'''
    
    def str=/"hello how
    you$ password doing/
    
    def str=$/"hello how
    you$ password doing/$
    

    *Formatting is the same as in OP