我想用HTMLAgilityPack提取html表。因为我想从中提取数据的网站已将名称,地址,邮政编码和城市放在同一个字符串中,我使用了
string nawhtml = cols[0].InnerHtml;
获取HTML代码,现在我想使用正则表达式来分隔名称,街道,邮政编码和地名,并将其放在c#中的单独字符串中。我从HTMLAgilibilitypack获得的代码是:
<b>Name</b><br>
Street<br>
Postalcode Placename<br>
这是已编写的代码:
Regex match1 = new Regex(@"<b>\s*(.+?)\s*</b><br>");
Match naamtankstation = match1.Match(nawhtml);
Console.WriteLine("Naam : " + naamtankstation.Groups[1].Value);
Regex match2 = new Regex(@"</b><br>\s*(.+?)\s*<br>");
Match straattankstation = match2.Match(nawhtml);
Console.WriteLine("Straat : " + straattankstation.Groups[1].Value);
Regex match3 = new Reg**strong text**ex(@"<br>{2,}\s*(.+?)\s*<br>");
Match postcodetankstation = match3.Match(nawhtml);
Console.WriteLine(postcodetankstation.Groups[1].Value);
但最后一个正则表达式不起作用。这不是我尝试过的唯一一件事。
如何制作正则表达式匹配女巫明白我想将邮政编码和地名放在不同的字符串中?
例如,这是我写的代码。
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using System.Data;
using System.Net;
using System.Text.RegularExpressions;
namespace AutoApp_Win32Server
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("APP.\n\n");
Console.WriteLine("APP.");
HtmlWeb web = new HtmlWeb();
HtmlDocument doc1 = web.Load("http://brandstofprijzen.info/?postcode=&plaats=8801&afstand=25&brandstof=Diesel&zoeken=Zoeken");
HtmlNodeCollection tables = doc1.DocumentNode.SelectNodes("/html/body/center/table");
HtmlNodeCollection rows = tables[13].SelectNodes(".//tr");
string makeSpace = " ";
for (int i = 1; i < rows.Count; ++i)
{
HtmlNodeCollection cols = rows[i].SelectNodes(".//td");
string nawhtml = cols[0].InnerHtml;
string brandstof = cols[1].InnerText;
string prijs = cols[2].InnerText;
string datum = cols[3].InnerText;
Regex match1 = new Regex(@"<b>\s*(.+?)\s*</b><br>");
Match naamtankstation = match1.Match(nawhtml);
Console.WriteLine("Naam : " + naamtankstation.Groups[1].Value);
Regex match2 = new Regex(@"</b><br>\s*(.+?)\s*<br>");
Match straattankstation = match2.Match(nawhtml);
Console.WriteLine("Straat : " + straattankstation.Groups[1].Value);
Regex match3 = new Regex(@"<br>{2,}\s*(.+?)\s*<br>");
Match postcodetankstation = match3.Match(nawhtml);
Console.WriteLine("Postcode : " + postcodetankstation.Groups[1].Value);
// Console.WriteLine("naw : " + nawhtml);
Console.WriteLine("Brandstof : " + brandstof);
Console.WriteLine("Prijs : " + prijs);
Console.WriteLine("Datum : " + datum);
Console.WriteLine(makeSpace);
Console.WriteLine(makeSpace);
}
Console.ReadKey();
}
}
}
答案 0 :(得分:0)
你可以试试这个
<br>([\w]+) ([\w]+)<br>
答案 1 :(得分:0)
由于惰性求值程序(?
),你的正则表达式不起作用;它会强制您的评估跳过Postalcode和Placename之间的空格。
尝试使用<br>\s(.+)<br>
。但是,这也会匹配Street,因此您可能需要调整代码。 AFAIK我认为HTMLAgilityPack会沿着换行符进行拆分,所以如果格式始终相同,您可以尝试按索引选择字段。