c# - 使用正则表达式获取部分匹配值

标签 c# regex

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

使用了这个表达式:

@"<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 属性 值。

如果不在 extractedValue 上使用 Substring 是否可以只获取那部分匹配?

最佳答案

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

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

关于c# - 使用正则表达式获取部分匹配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30899422/

相关文章:

c# - "System.IO.IOException: The process cannot access the file ' C :\Test\test. 文本 ' because it is being used by another process"

C#.NET : Showing a simple list with a 32x32 icon column and a 2 line text column

c# - "FreshIOC.Container.Register"有什么作用?

c# - 使用正则表达式查找并替换特定数字

javascript - 捕获 url 的第一部分

c# - 如何动态获取typeof()

c# - 由于出现奇怪的错误,Xamarin.Forms Android 项目无法编译

python - python中的正则表达式: findall

c++ - 使用正则表达式排除 C++ 中的子文件夹

php - 使用 smarty 隐藏电子邮件域