Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用正则表达式从字符串中删除标点符号_C#_Regex - Fatal编程技术网

C# 使用正则表达式从字符串中删除标点符号

C# 使用正则表达式从字符串中删除标点符号,c#,regex,C#,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]",

我对正则表达式非常不好,但我想删除所有这些“$#@!?/*&^-+在字符串中

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 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;
我还将代码存储在这里以备将来使用:

真诚地

贾斯汀·根戈


为什么不简单地运行一个字符串。替换?性能无疑会更好,代码也会更易于引导。这里已经回答了这个问题:@Tejs的可能重复:性能可能更好,也可能不更好,这取决于字符串的长度和需要替换的字符数。此外,代码将ld不一定不那么易读。很多人都不喜欢使用正则表达式,因为它们看起来确实很神秘,但就像其他代码一样-注释它们会有帮助。@Josh M。-所有这些都是有效的观点。但是,我同意代码应该是自文档化的观点;如果您必须注释以解释某些代码,则n该代码本身对我来说不够清楚=DI在\w\supdated我的答案时获得无法识别的转义序列…你只需要转义斜杠。这是一个漂亮的答案。我一直在寻找替换所有标点符号的方法,我从来没有想过只保留所有非标点符号(用\w和\s表示更容易).小心点,我认为
\w
字符组允许下划线,
\u
@mikeneeson这是真的,但这正是问题所要求的。嗨,丹尼尔,很高兴这么做。很抱歉,我最初没有这样做。