我对正则表达式真的很糟糕,但我想从字符串中删除所有这些
.,;:'"$#@!?/\*&^-+
。
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。贾斯汀·根戈
这可能会做你想做的事:
Regex.Replace("This is a string...", @"\p{P}", "");
参见正则表达式:匹配除 . 之外的任何标点符号。和_
和https://www.regular-expressions.info/posixbrackets.html