Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove special characters in the string in java?

How to remove special characters in the string except "- _". Now I use:

replaceAll("[^\\w\\s]", "")

it remove all special character but i want to keep "- _" . Can anyone tell me how should I do?

like image 488
Minato Avatar asked Sep 13 '26 06:09

Minato


2 Answers

Use replaceAll("[^\\w\\s\\-_]", "");

What I did was add the underscore and hyphen to the regular expression. I added a \\ before the hyphen because it also serves for specifying ranges: a-z means all letters between a and z. Escaping it with \\ makes sure it is treated as an hyphen.

like image 174
zmbq Avatar answered Sep 14 '26 19:09

zmbq


This might help:

replaceAll("[^a-zA-Z0-9_-]", "");

like image 28
nKn Avatar answered Sep 14 '26 19:09

nKn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!