![](/img/trans.png)
[英]Is it possible to get the specific part of a regex that matched the string
[英]Get part of matched value with 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
下得到什么match.Groups["Url"].Value
很简单http://www.somepage.com/someotherpage
在href
attribute
值之后没有任何内容。
是否有可能获得比赛的那一部分,而无需使用Substring
上extractedValue
?
你快到了。 正则表达式中只有一个小的变化,不允许匹配集中的引号。
<a .*href=""(?<Url>([^"]*))(?="")""
//^^^^ This is what i changed.
也许这会奏效。 不幸的是我现在没时间测试它:
"<a[^>]*href=\"(?<Url>([^\"]+))\"[^>]*>"
以下应该有效:
<a .*href=""(?<Url>(.+?))(?="")""
问题在于(。*)*是贪婪的。 +? “匹配前一个元素一次或多次,但尽可能少”,因此它将停在第一个引号处。 有关正则表达式中贪婪的更多信息,可以查看Regex教程 - 使用Star和Plus重复
使用这种模式,更不用说在不使用.*
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.