【问题标题】:Regex matches online but not in C# code正则表达式在线匹配,但不在 C# 代码中
【发布时间】:2017-02-21 10:04:31
【问题描述】:

这个正则表达式在网上regex testers 工作,但是当我尝试这段代码时,正则表达式不匹配。

 Regex regex = new Regex(@"^\.lnr-(.*)\:before \{$", RegexOptions.Compiled | RegexOptions.Multiline);

        string css = System.IO.File.ReadAllText(Server.MapPath("/linearicons-free.css"));
        foreach (Match match in regex.Matches(css))
        {
           //doing sth 
        }

我错过了什么?

【问题讨论】:

  • 请发布一个minimal reproducible example,其中包含一个字符串,该正则表达式在您希望它成功但失败的地方进行了测试。
  • 看来$\n 的开头匹配,但由于文件包含\r\n,因此您需要在模式中明确提及这一点。试试这个模式:@"^\.lnr-(.*)\:before \{\r$"@"^\.lnr-(.*)\:before \{\s?$"。这似乎记录在Anchors in Regular Expressions 下。
  • 字符串输入在在线正则表达式演示链接中。但也可以从demos.themecycle.com/eduhtml/edu/css/linearicons-free.css 联系到
  • 这很有效@LasseV.Karlsen 非常感谢你

标签: c# asp.net regex asp.net-mvc newline


【解决方案1】:

当 C# 解析字符串时,末尾有一个\n。 所以你的 pattern^\.lnr-(.*):before \{$ 失败了,因为你期望的最后一个字符是 {

将模式更改为^\.lnr-(.*):before \{\s$,它应该可以工作。

您可以测试 .NET 正则表达式 here 而不是 regex101.com

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多