Regular expression to remove all other characters except a-z, A-Z, 0-9 and replace " " to "-" from a string

Niladri.biswas
Posted by Niladri.biswas under C# category on | Points: 40 | Views : 8720
There is a requirement which states as Is there any way to remove all other characters except a-z, A-Z, 0-9 and replace " " to "-" from a string .

Here is what I have come out with

string str = "Hello this is a string...Phno Numbner: 9665110000;;;;Are u happy?[]";         

var result = Regex.Replace(Regex.Replace(str, "\\s+", "-"), "[^a-zA-Z0-9-]+", "");


Explanation

First we will replace the " " to "-".

var res1 = Regex.Replace(str, "\\s+", "-")


This becomes the input for the next one

var res2 = Regex.Replace(res1, "[^a-zA-Z0-9-]+", "");


Output

Hello-this-is-a-stringPhno-Numbner-9665110000Are-u-happy


Thanks

Comments or Responses

Login to post response