Translate Perl regular expressions to .NET

前端 未结 3 517
陌清茗
陌清茗 2020-11-29 02:47

I have some useful regular expressions in Perl. Is there a simple way to translate them to .NET\'s dialect of regular expressions?

If not, is there a concise referen

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 03:36

    They were designed to be compatible with Perl 5 regexes. As such, Perl 5 regexes should just work in .NET.

    You can translate some RegexOptions as follows:

    [Flags]
    public enum RegexOptions
    {
      Compiled = 8,
      CultureInvariant = 0x200,
      ECMAScript = 0x100,
      ExplicitCapture = 4,
      IgnoreCase = 1,                 // i in Perl
      IgnorePatternWhitespace = 0x20, // x in Perl
      Multiline = 2,                  // m in Perl
      None = 0,
      RightToLeft = 0x40,
      Singleline = 0x10               // s in Perl
    }
    

    Another tip is to use verbatim strings so that you don't need to escape all those escape characters in C#:

    string badOnTheEyesRx    = "\\d{4}/\\d{2}/\\d{2}";
    string easierOnTheEyesRx = @"\d{4}/\d{2}/\d{2}";
    

提交回复
热议问题