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

时间:2014-11-20 14:12:50

标签: regex vb.net string

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

例如“[one @!two three-four]”应该变为“one two three-four”

我尝试使用str = Regex.Replace(strTemp,“^ [ - _,A-Za-z0-9] $”,“”)。Trim()但它不起作用。我也尝试了一些,但他们要么摆脱空白,要么不替换所有特殊的字符

3 个答案:

答案 0 :(得分:8)

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

试试这个。参见demo。替换empty string。参见演示。

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

方法:

不要尝试使用 replace 使用 replaceAll 例如:

String InputString= "[one@ !two    three-four]";

String testOutput = InputString.replaceAll("[\\[\\-!,*)@#%(&$_?.^\\]]", "").replaceAll("( )+", " ");

Log.d("THE OUTPUT", testOutput);

这将给出一二三四的输出。

解释:

.replaceAll("[\\[\\-!,*)@#%(&$_?.^\\]]", "") 这将替换第一个和最后一个括号之间的所有特殊字符[]

.replaceAll("( )+", " ") 用 1 个空格替换 1 个以上的空格

替换 - 符号:

只需像这样将符号添加到正则表达式 .replaceAll("[\\[\\-!,*)@#%(&$_?.^\\]]", "")

希望这会有所帮助:)

相关问题