【问题标题】:Repeat Groups to form objects重复组以形成对象
【发布时间】:2016-05-15 04:23:49
【问题描述】:

我有一个这样的 html 表格:

<table style="width:100%">
  <tr>
    <td class="country">Germany</td>
  </tr>
  <tr>
    <td class="city">Berlin</td>
  </tr>
  <tr>
    <td class="city">Cologne</td>
  </tr>
  <tr>
    <td class="city">Munich</td>
  </tr>
   <tr>
    <td class="country">France</td>
  </tr>
  <tr>
    <td class="city">Paris</td>
  </tr>
      <tr>
    <td class="country">USA</td>
  </tr>
  <tr>
    <td class="city">New York</td>
  </tr>
  <tr>
    <td class="city">Las Vegas</td>
  </tr>
</table>

从这个表中,我想生成像 Country 和 City 类的对象。 Country 会有一个城市列表。

现在解决问题: 创建一个正则表达式来获取所有国家和所有城市很容易,但我想知道我是否可以让城市的组重复直到下一个国家开始?我需要这样做,因为如果我将它们放在单独的正则表达式匹配中,我无法以编程方式确定哪个城市属于哪个国家。

应该是这样的(快速而肮脏的解决方案):

country">([\w]*)<{.*\n.*\n.*\n.*"city">([\w]*)}

花括号应该重复,直到出现下一个国家/地区项目。

如果您对如何在 c# 中从 html 表中获取对象有完全不同的想法,请告诉我!

提前致谢!

【问题讨论】:

  • 你想要的数据列表,datatable,var..
  • 你在用jquery吗?
  • 我不关心格式。我用的是c#,对html代码没有任何影响。
  • 你应该使用 HTML 解析器
  • 好吧,但是如何使用 html 解析器来做到这一点?我唯一的想法是在 class="country" 处拆分表,但我想知道是否有更好的方法

标签: regex html-agility-pack


【解决方案1】:

同意对于任何重要的 HTML,都应该使用 HTML 解析器,如 HtmlAgilityPack。话虽如此,如果您的 HTML 与上面的 sn-p 一样简单,即使字符串中有多个换行符,它也可以:

string HTML = @"
<table style='width:100%'>
    <tr><td class='country'>Germany</td></tr>
    <tr><td class='city'>Berlin</td></tr>
    <tr><td class='city'>Cologne</td></tr>
    <tr><td class='city'>Munich</td></tr>
    <tr><td class='country'>France</td></tr>
    <tr><td class='city'>Paris</td></tr>
    <tr><td class='country'>USA</td></tr>
    <tr><td class='city'>New York</td></tr>
    <tr><td class='city'>Las Vegas</td></tr>
</table>";

var regex = new Regex(
    @"
        class=[^>]*?
        (?<class>[-\w\d_]+)
        [^>]*>
        (?<text>[^<]+)
        <
    ",
    RegexOptions.Compiled | RegexOptions.IgnoreCase 
    | RegexOptions.IgnorePatternWhitespace
);

var country = string.Empty;
var Countries = new Dictionary<string, List<string>>();
foreach (Match match in regex.Matches(HTML))
{
    string countryCity = match.Groups["class"].Value.Trim();
    string text = match.Groups["text"].Value.Trim();
    if (countryCity.Equals("country", StringComparison.OrdinalIgnoreCase))
    {
        country = text;
        Countries.Add(text, new List<string>());
    }
    else
    {
        Countries[country].Add(text);
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2018-07-05
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 2019-05-16
    • 2017-11-06
    • 2019-02-03
    相关资源
    最近更新 更多