且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式替换无效字符

更新时间:2022-05-20 22:37:50

尝试以下正则表达式:

Regex regex = new Regex(@"[\s,:.;/\\]+");
string cleanText = regex.Replace(messyText, "").ToUpper();

\s 是字符类等效项到 [\t\r\n]

如果只想保留字母数字字符,而不是将存在的每个非字母数字字符添加到字符类中,则可以执行以下操作:

If you just want to preserve alphanumeric characters, instead of adding every non-alphanumeric character in existence to the character class, you could do this:

Regex regex = new Regex(@"[\W_]+");
string cleanText = regex.Replace(messyText, "").ToUpper();

其中 \W 是非文字字符(不是 [^ a-zA-Z0-9 _] )。

Where \W is any non-word character (not [^a-zA-Z0-9_]).