I would like a regular expression for removing all special characters except an underscore. I can replace all special characters, but I don’t know how to keep the underscores. Here’s the code for removing all speial characters,
String myname= "!john_smith@#-".replaceAll("\\p{Punct}+", "");
Any ideas how to modify the regex so that I keep underscores?
Thanks,
Patrick
Well
\\p...is the same as[^\\P...](negated character class of characters not having the property), and then you could put the underscore in there as well:Alternatively, use a negative lookahead
Also, seeing your example, maybe something as simple as this will be enough for you:
Will remove everything except for letters, digits, underscores and whitespace.