2014-09-03 76 views
0

我有下面的代码:如何使用RegEx从HTML中提取某些数据?

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

我想用正则表达式的输出标记之间的数据,像这样:

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

+3

(http://stackoverflow.com/a/1732454/102937 ) – 2014-09-03 15:21:16

回答

1

您不应该使用正则表达式来解析html,请使用HTML解析器inste广告。

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

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

Working demo

enter image description here 比赛信息:

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

这应该摆脱一切之间的标签,并输出其余的空间分开:

$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 
0

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.

相关问题