Looking for help where given any string, return a string with alphanumeric characters only and replace all non-alphanumeric characters with _
so string
“ASD@#$123” becomes
“ASD___123”
etc
thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For most string operations, you would be better off (in terms of
both efficiency andconciseness) if you use regular expressions rather than LINQ:If you want to preserve any Unicode alphanumeric character, including non-ASCII letters such as
é, we can use the non-word character class to make it even simpler:For the sake of comparison, here is the same conversion done using LINQ (allowing just ASCII letters and digits):
Or, if
Char.IsLetterOrDigitmeets your requirements:Note that
Char.IsLetterOrDigitwill allow non-ASCII letters, and is comparable to the\wword character class whose negation was used in our second example.Edit: As Steve Wortham has observed, the LINQ versions are actually more than 3× faster than the regex (even when a
Regexinstance is created in advance withRegexOptions.Compiledand re-used).