C# 模式后匹配字符的正则表达式
我试图在长字符串中的模式之后提取字符串,这基本上是页面的HTML输出 比如,;我需要从这个字符串中提取href标记的目标C# 模式后匹配字符的正则表达式,c#,regex,C#,Regex,我试图在长字符串中的模式之后提取字符串,这基本上是页面的HTML输出 比如,;我需要从这个字符串中提取href标记的目标 <h2 class=\ "product-name\"><a href=\"/erkek-ayakkabi-spor-gri-17sfd3007141340-p\" title=\"...">...</a></h2>\r\n \r\n 我需要的是:erkek-ayakkabi-spor-gri-17sfd3007141340
<h2 class=\ "product-name\"><a href=\"/erkek-ayakkabi-spor-gri-17sfd3007141340-p\" title=\"...">...</a></h2>\r\n
\r\n
我需要的是:erkek-ayakkabi-spor-gri-17sfd3007141340-p
但我也需要找到与上面的字符串相似的字符串。因此,我需要在HTML字符串中的class=\“product name\”
之后搜索href
标记
我如何才能做到这一点?请检查此项
正则表达式:
class=\"product-name\"(.*)<a\shref=\"(.*?)\"
class=\“产品名称\”(.*)
C#代码:
使用系统;
使用System.Text.RegularExpressions;
公共课程
{
公共静态void Main()
{
字符串数据=“\r\n\r\n\r\n”;
//string regex=“class=\”产品名称\”(.*).看。我正在编写一个已经编写好的代码,我只需要做一点小小的更改。我现在没有时间从根本上改变我们解析html的方式。也许以后。该死,我只是写了完全相同的代码…:)为什么需要第一组?如果在a
之后class=“product name”之前有其他标记“
。我还是不明白。*
就足够了,为什么(.*)
class=\"product-name\".*<a\shref=\"(.*?)\"
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string data = "<h2 class=\"product-name\"><a href=\"erkek-ayakkabi-spor-gri-17sfd3007141340-p\" title=\"...\">...</a></h2>\r\n<h2 class=\"test-name\"><a href=\"erkek-ayakkabi-spor-gri-17sfd3007141340-p\" title=\"...\">...</a></h2>\r\n<h2 class=\"product-name\"><a href=\"erkek-ayakkabi-spor-gri-17sfd3007141340-p\" title=\"...\">...</a></h2>\r\n";
//string regex = "class=\"product-name\"(.*)<a\\shref=\"(.*?)\"";
string regex = "class=\"product-name\".*<a\\shref=\"(.*?)\"";
var matches = Regex.Matches(data, regex, RegexOptions.Multiline);
foreach(Match item in matches)
{
//Console.WriteLine("Value: " + item.Groups[2]);
Console.WriteLine("Value: " + item.Groups[1]);
}
}
}