I've tried new Regex("a-zA-Z0-9").Replace(myString, string.Empty)
but开发者_C百科 apparently that is not correct.
The correct regex would be [a-zA-Z0-9]
.
The regular expression a-zA-Z0-9
matches the literal string a-zA-Z0-9
whereas the character class [a-zA-Z0-9]
matches any of the characters in the ranges a-z
, A-Z
or 0-9
.
In addition, these classes have shorthands (sort of).
\d
represents the class of digits, that is[0-9]
.\w
represents the class of alphanumerical characters, as well as underscore, that is[0-9A-Za-z_]
.
Useful links:
- Character classes on Regular-Expressions.info.
Just for laughs you could also do it like this....
string newString = new string(s.Where(c => !char.IsLetterOrDigit(c)).ToArray());
(much, much slower the first time through...then subsequent runs, faster)
精彩评论