【问题标题】:Get part of matched value with regex使用正则表达式获取部分匹配值
【发布时间】:2015-09-03 03:37:40
【问题描述】:

我正在尝试获取字符串的一部分。

使用了这个表达方式:

@"<a .*href=""(?<Url>(.*))(?="")"""

要匹配的示例数据:

var input = @"<html lang=""en"">
    <head>
        <link href=""http://www.somepage.com/c/main.css"" rel=""stylesheet"" type=""text/css"" />

        <link rel=""canonical"" href=""http://www.somepage.com"" />
        <script src=""http://www.somepage.com/professional/bower_components/modernizr/modernizr.js"" type=""text/javascript""></script>
    </head>
        <body>
            <header>
                <div>
                    <div>
                        <a aria-haspopup=""true"" href=""http://www.somepage.com/someotherpage""><img src=""http://www.somepage.com/i/sprite/logo.png"" alt=page"" /></a>
                    </div>
                </div>
            </header>
        </body>
    </html>"

现在我能够得到这个值:

http://www.somepage.com/someotherpage\"><img src=""http://www.somepage.com/i/sprite/logo.png"" alt=page"" /></a>

使用此代码:

var regexPattern = new Regex(PATTERN, RegexOptions.IgnoreCase);
var matches = regexPattern.Matches(httpResult);
foreach (Match match in matches)
{
    // here I'm getting this value 
    var extractedValue = match.Groups["Url"].Value; // it's value is http://www.somepage.com/someotherpage\"><img src=""http://www.somepage.com/i/sprite/logo.png"" alt=page"" /></a>
}

我想在match.Groups["Url"].Value 下得到的是简单的http://www.somepage.com/someotherpage,在href attribute 值之后没有任何内容。

extractedValue 上不使用Substring 是否可以只获得匹配的那部分?

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    也许这会奏效。不幸的是,我现在没有时间测试它:

    "<a[^>]*href=\"(?<Url>([^\"]+))\"[^>]*>"
    

    【讨论】:

      【解决方案2】:

      你快到了。正则表达式中的一个小改动就是不允许匹配集中的引号。

      <a .*href=""(?<Url>([^"]*))(?="")""
                        //^^^^ This is what i changed.
      

      【讨论】:

        【解决方案3】:

        以下应该有效:

        <a .*href=""(?<Url>(.+?))(?="")""
        

        问题在于 (.*) 中的 * 是贪婪的。 +? "Matches the previous element one or more times, but as few times as possible" 所以它会停在第一个引号。更多关于正则表达式贪婪的信息,可以查看Regex Tutorial - Repetition with Star and Plus

        【讨论】:

          【解决方案4】:

          改用这种模式,在不使用.* meme 时减少回溯(处理速度更快)。该模式还使用\x22 作为",以便更轻松地操作模式,因为它避免了 C# 文字混淆问题。

          Regex.Matches(input, @"<a.+href=\x22(?<Url>[^\x22]+).+/a>")
               .OfType<Match>()
               .Select (mt => mt.Groups["Url"].Value);
               // Result = http://www.somepage.com/someotherpage
          

          【讨论】:

            猜你喜欢
            • 2011-06-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-04-12
            • 2017-11-29
            • 2017-06-23
            • 2021-02-09
            相关资源
            最近更新 更多