这里脑子有点僵硬,所以我希望得到一些指示,基本上我需要提取特定 div 标签的内容,是的,我知道正则表达式通常不被批准用于此,但它是一个简单的网络在没有嵌套 div 的地方抓取应用程序。
我正在尝试匹配这个:
<div class="entry">
<span class="title">Some company</span>
<span class="description">
<strong>Address: </strong>Some address
<br /><strong>Telephone: </strong> 01908 12345
</span>
</div>
简单的vb代码如下:
Dim myMatches As MatchCollection
Dim myRegex As New Regex("<div.*?class=""entry"".*?>.*</div>", RegexOptions.Singleline)
Dim wc As New WebClient
Dim html As String = wc.DownloadString("http://somewebaddress.com")
RichTextBox1.Text = html
myMatches = myRegex.Matches(html)
MsgBox(html)
'Search for all the words in a string
Dim successfulMatch As Match
For Each successfulMatch In myMatches
MsgBox(successfulMatch.Groups(1).ToString)
Next
如有任何帮助,我们将不胜感激。
最佳答案
您的正则表达式适用于您的示例。但是,应该进行一些改进:
<div[^<>]*class="entry"[^<>]*>(?<content>.*?)</div>
[^<>]*
意思是“匹配除尖括号之外的任意数量的字符”,确保我们不会不小心跳出我们所在的标签。
.*?
(注意 ?
)表示“匹配任意数量的字符,但尽可能少”。这避免了从第一个匹配到最后一个 <div class="entry">
在您的页面中标记。
但是您的正则表达式本身应该仍然匹配某物。也许你没有正确使用它?
我不懂 Visual Basic,所以这只是瞎猜,但 RegexBuddy 建议采用以下方法:
Dim RegexObj As New Regex("<div[^<>]*class=""entry""[^<>]*>(?<content>.*?)</div>")
Dim MatchResult As Match = RegexObj.Match(SubjectString)
While MatchResult.Success
ResultList.Add(MatchResult.Groups("content").Value)
MatchResult = MatchResult.NextMatch()
End While
我建议不要比这更进一步地采用正则表达式方法。如果你坚持,你最终会得到一个像下面这样的怪物正则表达式,它只有在 div
的形式下才有效。的内容永远不会改变:
<div[^<>]*class="entry"[^<>]*>\s*
<span[^<>]*class="title"[^<>]*>\s*
(?<title>.*?)
\s*</span>\s*
<span[^<>]*class="description"[^<>]*>\s*
<strong>\s*Address:\s*</strong>\s*
(?<address>.*?)
\s*<strong>\s*Telephone:\s*</strong>\s*
(?<phone>.*?)
\s*</span>\s*</div>
或(看看 VB.NET 中多行字符串的乐趣):
Dim RegexObj As New Regex(
"<div[^<>]*class=""entry""[^<>]*>\s*" & chr(10) & _
"<span[^<>]*class=""title""[^<>]*>\s*" & chr(10) & _
"(?<title>.*?)" & chr(10) & _
"\s*</span>\s*" & chr(10) & _
"<span[^<>]*class=""description""[^<>]*>\s*" & chr(10) & _
"<strong>\s*Address:\s*</strong>\s*" & chr(10) & _
"(?<address>.*?)" & chr(10) & _
"\s*<strong>\s*Telephone:\s*</strong>\s*" & chr(10) & _
"(?<phone>.*?)" & chr(10) & _
"\s*</span>\s*</div>",
RegexOptions.Singleline Or RegexOptions.IgnorePatternWhitespace)
(当然,现在您需要存储 MatchResult.Groups("title")
等的结果...)
关于用于提取 <div> 标记内容的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11306596/