4

I am looking to remove special characters from a string using groovy, i'm nearly there but it is removing the white spaces that are already in place which I want to keep. I only want to remove the special characters (and not leave a whitespace). I am running the below on a PostCode L&65$$ OBH

def removespecialpostcodce = PostCode.replaceAll("[^a-zA-Z0-9]+","")
log.info removespecialpostcodce 

Currently it returns L65OBH but I am looking for it to return L65 OBH

Can anyone help?

Rao
  • 20,781
  • 11
  • 57
  • 77
csman
  • 81
  • 1
  • 2
  • 9

2 Answers2

9

Use below code :

 PostCode.replaceAll("[^a-zA-Z0-9 ]+","")

instead of

 PostCode.replaceAll("[^a-zA-Z0-9]+","")
hedha
  • 266
  • 1
  • 2
  • 10
2

To remove all special characters in a String you can use the invert regex character:

String str = "..\\.-._./-^+* ".replaceAll("[^A-Za-z0-1]","");
System.out.println("str: <"+str+">");

output:

str: <>  

to keep the spaces in the text add a space in the character set

String str = "..\\.-._./-^+* ".replaceAll("[^A-Za-z0-1 ]","");
System.out.println("str: <"+str+">");

output:

str: < >  
velocity
  • 1,630
  • 21
  • 24