包含正则表达式定界符的简单且经过测试的在线正则表达式在C#代码中不起作用 [英] Simple and tested online regex containing regex delimiters does not work in C# code

查看:77
本文介绍了包含正则表达式定界符的简单且经过测试的在线正则表达式在C#代码中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个正则表达式:

I have a regex like this:

name = dr-det-fb.ydp.eu/ebook/trunk/annotations/ctrl.php/api1751-4060-1193-0487
name = Regex.Replace(name, @"/\W/g", "");

此正则表达式应替换 /,-,。与。
但这不是,有人可以向我解释原因吗?

This regex should replace "/", "-", "." with "". But it doesn't, can someone explain me why?

推荐答案

请勿使用正则表达式分隔符:

Do not use regex delimiters:

name = Regex.Replace(name, @"\W", "");

在C#中,不能使用正则表达式定界符,因为声明正则表达式的语法不同于PHP,Perl或JavaScript或其他支持< action> /< pattern>(// substituiton>)/修饰符 regex声明的

In C#, you cannot use regex delimiters as the syntax to declare a regular expression is different from that of PHP, Perl or JavaScript or others that support <action>/<pattern>(/<substituiton>)/modifiers regex declaration.

只是为了避免术语混淆:肯定支持内联修饰符(强制不区分大小写的搜索,多行,单行,详细模式和其他模式),可以代替相应的 RegexOptions 标志(尽管可能的 RegexOptions 标志数量比内联修饰符高)。不过, regex分隔符根本不影响regex模式,它们只是声明语法的一部分,并且不影响模式本身。说,它们只是; 或换行符分隔代码行的替代。

Just to avoid terminology confusion: inline modifiers (enforcing case-insensitive search, multiline, singleline, verbose and other modes) are certainly supported and can be used instead of the corresponding RegexOptions flags (though the number of possible RegexOptions flags is higher than that of inline modifiers). Still, regex delimiters do not influence the regex pattern at all, they are just part of declaration syntax, and do not impact the pattern itself. Say, they are just kind of substitutes for ; or newline separating lines of code.

在C#中,正则表达式分隔符不需要,因此不受支持。 Perl样式的 s / \W // g 将写为 var replace = Regex.Replace(str,@ \W, string.Empty); 。依此类推。

In C#, regex delimiters are not necessary and thus are not supported. Perl-style s/\W//g will be written as var replaced = Regex.Replace(str, @"\W", string.Empty);. And so on.

这篇关于包含正则表达式定界符的简单且经过测试的在线正则表达式在C#代码中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆