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

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.

Leave a Comment