我真的不擅长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?!.", @"[^ws]", "");
这意味着:
[ #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
真诚。贾斯汀Gengo
http://www.justingengo.com这可能是你想要的:
Regex.Replace("This is a string...", @"p{P}", "");
参见正则表达式:匹配除。和_
和https://www.regular-expressions.info/posixbrackets.html