cancel
Showing results for 
Search instead for 
Did you mean: 

Seeking For Groovy

ganiganesh
Explorer
0 Kudos

Please share a groovy to replace all Special characters in a string, we can do the same in mapping as if now we have to replace some special characters but in future if we need to replace some other character means on that time we need add.

Thanks & Regards,

Dhanush.

MortenWittrock
Active Contributor

So, you use my answer but accept your own, without even an upvote? Not a good look.

MortenWittrock
Active Contributor
0 Kudos

No harm done.

Have a nice weekend,

Morten

Accepted Solutions (1)

Accepted Solutions (1)

MortenWittrock
Active Contributor

Hi Dhanush

You can use the replaceAll method of the String class in Groovy. You pass it a regular expression and a replacement string. Here's a simple function using the method:

def String replaceSpecialChars(String toReplace, String replaceWith) {
    toReplace.replaceAll(~/[^\w\s]/, replaceWith)
}

The regular expression replaces everything that is not:

  • A letter
  • A number
  • Whitespace

You can update the regular expression as needed.

If you want to remove instead of replace, simply pass the empty string as the replacement value.

Regards,

Morten

ganiganesh
Explorer
0 Kudos

Thanks Morten.

MortenWittrock
Active Contributor
0 Kudos

Hi ganiganesh

No problem. If an answer in the Q&A area solves your problem, please remember to accept it. You can also show your appreciation of helpful answers by upvoting them.

Regards,

Morten

Answers (0)