[英]Remove punctuation from string with Regex
我對正則表達式真的很不好,但我想從字符串中刪除所有這些。,;:'"$#@??/*&^-+
string x = "This is a test string, with lots of: punctuations; in it?!.";
我怎樣才能做到這一點?
首先,請閱讀此處以獲取有關正則表達式的信息。 值得學習。
你可以使用這個:
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.
最后它顯示“將任何不是單詞字符或空格字符的字符替換為空字符”。
此代碼顯示了完整的 RegEx 替換過程,並提供了一個示例 Regex,它只在字符串中保留字母、數字和空格 - 用空字符串替換所有其他字符:
//Regex to remove all non-alphanumeric characters
System.Text.RegularExpressions.Regex TitleRegex = new
System.Text.RegularExpressions.Regex("[^a-z0-9 ]+",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
string ParsedString = TitleRegex.Replace(stringToParse, String.Empty);
return ParsedString;
而且我還在這里存儲了代碼以供將來使用: http://code.justingengo.com/post/Use%20a%20Regular%20Expression%20to%20Remove%20all%20Punctuation%20from%20a%20String
真摯地,
S.賈斯汀·根戈
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.