Simple and tested online regex containing regex delimiters does not work in C# code

后端 未结 1 915
无人共我
无人共我 2020-11-22 10:18

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\", \"\");


        
相关标签:
1条回答
  • 2020-11-22 10:33

    Do not use regex delimiters:

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

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题