Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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# Regex删除字符和提供的单词_C#_Regex - Fatal编程技术网

C# Regex删除字符和提供的单词

C# Regex删除字符和提供的单词,c#,regex,C#,Regex,我需要一个正则表达式,将只允许字母数字字符,并删除某些完整的字 例如: 输入字符串:这是约翰尼·布拉沃的祖父 结果字符串:johny bravos dad 用空字符串替换的单词/字符:this,is,,,grand 以下是我到目前为止的情况: var input = "this-is-johny-bravo's-grand-dad"; var regex = new Regex(@"([^a-z0-9\-][\b(this|is|grand)\b]?)"); var result = regex

我需要一个正则表达式,将只允许字母数字字符,并删除某些完整的字

例如:

输入字符串:这是约翰尼·布拉沃的祖父

结果字符串:johny bravos dad

用空字符串替换的单词/字符:this,is,,,grand

以下是我到目前为止的情况:

var input = "this-is-johny-bravo's-grand-dad";
var regex = new Regex(@"([^a-z0-9\-][\b(this|is|grand)\b]?)");
var result = regex.Replace(input, "");

结果似乎没有撇号,但不幸的是仍然包含被拒绝的完整单词。

您还需要将字符类添加到alternation:

new Regex(@"\b(this|is|grand)\b-?|[^a-z0-9-]");

你的表情太复杂了。试一试

\b(this|is|grand|')\b-? 细分:

( # group 1 \b(this|is|grand)\b # any of these words | # or [^a-z0-9-] # any character except one of these ) # end group 1 -? # optional dash at the end (#第一组) \(这是伟大的)这些词中的任何一个 |#或 [^a-z0-9-]#除其中一个字符外的任何字符 )#终端组1 -? # 末端可选破折号
+1这可能比我更符合OP的意图。:)(虽然表达式中仍然存在语法错误,并且没有删除多余的破折号)看起来不错,但我只是删除了您的额外“')”括号。谢谢@托马拉克:是的,我需要做点什么来处理额外的破折号。@托马拉克:哎呀。修好了。谢谢:)word边界是否适用于
?我的意思是我不确定。否则这是很好的缩短版本。@Rohit是的,是偶然的。单词边界是双向的,一个出现在
(单词
“bravo”
)的前面,另一个出现在
“s”
)的后面。但这并不是OP的意思,所以先别管短版本,用长版本吧。谢谢你的解释块,它确实有助于理解语法。 ( # group 1 \b(this|is|grand)\b # any of these words | # or [^a-z0-9-] # any character except one of these ) # end group 1 -? # optional dash at the end