Reputation: 6899
I am looking for a regular expression to remove all special characters from a string, except whitespace. And maybe replace all multi- whitespaces with a single whitespace.
For example "[one@ !two three-four]"
should become "one two three-four"
I tried using str = Regex.Replace(strTemp, "^[-_,A-Za-z0-9]$", "").Trim()
but it does not work. I also tried few more but they either get rid of the whitespace or do not replace all the special characters.
Upvotes: 3
Views: 20373
Reputation: 175
METHOD:
instead of trying to use replace use replaceAll eg :
String InputString= "[one@ !two three-four]";
String testOutput = InputString.replaceAll("[\\[\\-!,*)@#%(&$_?.^\\]]", "").replaceAll("( )+", " ");
Log.d("THE OUTPUT", testOutput);
This will give an output of one two three-four.
EXPLANATION:
.replaceAll("[\\[\\-!,*)@#%(&$_?.^\\]]", "")
this replaces ALL the special characters present between the first and last brackets[]
.replaceAll("( )+", " ")
this replaces more than 1 whitespace with just 1 whitespace
REPLACING THE - symbol:
just add the symbol to the regex like this .replaceAll("[\\[\\-!,*)@#%(&$_?.^\\]]", "")
Hope this helps :)
Upvotes: 0
Reputation: 1
Use the regex [^\w\s]
to remove all special characters other than words and white spaces, then replace:
Regex.Replace("[one@ !two three-four]", "[^\w\s]", "").Replace(" ", " ").Trim
Upvotes: 0
Reputation: 67968
[ ](?=[ ])|[^-_,A-Za-z0-9 ]+
Try this.See demo.Replace by empty string
.See demo.
http://regex101.com/r/lZ5mN8/69
Upvotes: 10