vb.net 从字符串中删除除空格以外的特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27041684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:30:19  来源:igfitidea点击:

Remove special characters from a string except whitespace

regexvb.netstring

提问by Coding Duchess

I am looking for a regular expression to remove all special characters from a string, except whitespace. And maybe replace all multi- whitespaces with a single whitespace.

我正在寻找一个正则表达式来从字符串中删除所有特殊字符,除了空格。并且可能用一个空格替换所有的多个空格。

For example "[one@ !two three-four]"should become "one two three-four"

例如"[one@ !two three-four]"应该变成"one two three-four"

I tried using str = Regex.Replace(strTemp, "^[-_,A-Za-z0-9]$", "").Trim()but it does not work. I also tried few more but they either get rid of the whitespace or do not replace all the special characters.

我尝试使用 str = Regex.Replace(strTemp, "^[-_,A-Za-z0-9]$", "").Trim()但它不起作用。我还尝试了更多,但他们要么去掉空格,要么不替换所有特殊字符。

回答by vks

[ ](?=[ ])|[^-_,A-Za-z0-9 ]+

Try this.See demo.Replace by empty string.See demo.

试试这个。见empty string演示。替换为。见演示。

http://regex101.com/r/lZ5mN8/69

http://regex101.com/r/lZ5mN8/69

回答by missa

Use the regex [^\w\s]to remove all special characters other than words and white spaces, then replace:

使用正则表达式[^\w\s]删除除单词和空格以外的所有特殊字符,然后替换:

Regex.Replace("[one@ !two three-four]", "[^\w\s]", "").Replace("  ", " ").Trim