开发者

How do I get content from a table using its ID with a regex?

I need to sort a html string so I get the content I need. Now I need to loop through the table rows in a table that have an ID. How d开发者_Go百科o I do this with a regex?


Regular expressions cannot be used to parse HTML; HTML is not regular. Use a proper HTML parser library.


It depends on how regular the HTML text is. For example, given this table:

<table>
  <tr><td>1</td><td>Apple</td></tr>
  <tr><td>2</td><td>Ball</td></tr>
  <tr><td>3</td><td>Cookie</td></tr>
<table>

The following regex expression finds the IDs in the first column:

(?<=<tr><td>).*?(?=</td>)


If you run the page through an html-parser like BeautifulSoup, then you can prettify it so that this kind of regex has a chance. But if you are parsing the html anyway...


Try this

Dim HTML As String = contentText
Dim options As RegexOptions = RegexOptions.IgnoreCase Or RegexOptions.Singleline
Dim regex As Regex = New Regex("<table[^>]*>(.*)</table>", options)
Dim match As MatchCollection = regex.Matches(HTML)
Dim sb As StringBuilder = New StringBuilder
For Each items As Match In match
    sb.Append(items.ToString & vbLf)
Next
TextBox.Text = sb.ToString
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜