开发者

How do I remove all alphanumeric characters from a .NET string using the Regex class?

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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜