【问题标题】:How to extract certain data from HTML using RegEx?如何使用 RegEx 从 HTML 中提取某些数据?
【发布时间】:2014-09-03 15:18:10
【问题描述】:

我有以下代码:

<tr class="even">
            <td>
                Title1
            </td>
            <td>
                Name1
            </td>
            <td>
                Email1
            </td>
            <td>
                Postcode1
            </td>

我想使用 RegEx in 来输出标签之间的数据,如下所示:

标题1 名称1 电子邮件1 邮编1 标题2 名称2 电子邮件2 邮编2 ...

【问题讨论】:

标签: html regex powershell tags


【解决方案1】:

您不应该使用正则表达式来解析 html,而应使用 HTML 解析器。

无论如何,如果你真的想要一个正则表达式,你可以使用这个:

>\s+<|>\s*(.*?)\s*<

Working demo

比赛信息:

MATCH 1
1.  [51-57] `Title1`
MATCH 2
1.  [109-114]   `Name1`
MATCH 3
1.  [166-172]   `Email1`
MATCH 4
1.  [224-233]   `Postcode1`

【讨论】:

    【解决方案2】:

    这应该去掉标签之间的所有内容,并将剩余的空格分开输出:

    $text = 
    @'
    <tr class="even">
                <td>
                    Title1
                </td>
                <td>
                    Name1
                </td>
                <td>
                    Email1
                </td>
                <td>
                    Postcode1
                </td>
    '@
    
    $text -split '\s*<.+?>\s*' -match '\S' -as [string]
    
    Title1 Name1 Email1 Postcode1
    

    【讨论】:

      【解决方案3】:

      Don't use a regex. HTML 不是常规语言,因此无法使用正则表达式正确解析。大多数时候它会成功,但其他时候会失败。壮观。

      使用 Internet Explorer COM 对象从文件中读取 HTML:

      $ie = new-object -com "InternetExplorer.Application"
      $ie.visible = $false
      $ie.navigate("F:\BuildOutput\rt.html")
      $document = $ie.Document
      # This will return all the tables
      $document.getElementsByTagName('table')
      
      # This will return a table with a specific ID
      $document.getElementById('employees')
      

      Here's the MSDN reference for the document class.

      【讨论】:

        猜你喜欢
        • 2011-07-16
        • 2021-08-15
        • 1970-01-01
        • 2010-11-26
        • 2013-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多