2011-05-03 354 views
16

刪除標點我用正則表達式非常糟糕,但我想刪除所有這些,;:!?「」$#@/* &^- +一個字符串的從字符串與正則表達式

string x = "This is a test string, with lots of: punctuations; in it?!."; 

我怎樣才能做到這

+4

爲什麼就不能運行與string.replace?性能毫無疑問會更好,代碼將更易於啓動。 – Tejs 2011-05-03 15:24:57

+1

可能的重複[從字符串中去除標點符號的最佳方式](http://stackoverflow.com/questions/421616/best-way-to-strip-punctuation-from-a-string) – 2011-05-03 15:26:45

+0

@Tejs:性能可能或者可能不會更好,這取決於字符串的長度和需要替換的字符數。而且,代碼不一定會不太可讀。很多人不喜歡使用正則表達式,因爲它們看起來很神祕,但就像任何其他代碼一樣 - 評論它們會對此有所幫助。 – 2011-05-03 15:27:29

回答

46

首先,請read here對正則表達式的信息,這是值得我們學習

您可以使用此:?。

Regex.Replace("This is a test string, with lots of: punctuations; in it?!.", @"[^\w\s]", ""); 

這意味着:

[ #Character block start. 
^ #Not these characters (letters, numbers). 
\w #Word characters. 
\s #Space characters. 
] #Character block end. 

在讀取結束「取代這不是一個單詞字符或什麼也沒有空格字符的任意字符。」

+0

我在\ w \ s上得到了無法識別的轉義序列 – Sjemmie 2011-05-03 15:29:12

+0

更新我的答案......您只需要避開斜線。 – 2011-05-03 15:30:04

+0

我明白了,它工作正常 – Sjemmie 2011-05-03 15:33:40