使用正则表达式来获取所有标题来构建一个ToC(经典ASP)

问题描述:

我仍然尝试开发一个函数,它从HTML文本中提取所有标题(h1,h2,h3,..)的内容。使用正则表达式来获取所有标题来构建一个ToC(经典ASP)

我做了使用正则表达式一个简单的脚本,但由于一些奇怪的原因,只收集1场(最后一个)

这里我的示例代码:

Function RegExResults(strTarget, strPattern) 
    dim regEx 
    Set regEx = New RegExp 
    regEx.Pattern = strPattern 
    regEx.Global = True 
    regEx.IgnoreCase = True 
    regEx.Multiline = True 
    Set RegExResults = regEx.Execute(strTarget) 
    Set regEx = Nothing 
End Function 

htmlstr = "<h1>Documentation</h1><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p><h3 id=""one"">How do you smurf a murf?</h3><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.</p><h3 id=""two"">How do many licks does a giraffe?</h3><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>" 

regpattern = "<h([1-9]).*id=\""(.*)\"">(.*)</h[1-9]>" 

set arrayresult = RegExResults(htmlstr,regpattern) 
For each result in arrayresult 
    response.write "count: " & arrayresult.count & "<br><hr>" 
    response.write "0: " & result.Submatches(0) & "<br>" 
    response.write "1: " & result.Submatches(1) & "<br>" 
    response.write "2: " & result.Submatches(2) & "<br>" 
Next 

我需要提取所有标题加上每个人都知道什么样的标题是(1..9)以及用于跳转到正确的标题段落(#ID_value)的id值。

我希望有人能帮我找出为什么这不按预期工作。

谢谢

.*的在模式是贪婪的,但你需要懒惰收集每一个可能的匹配。相反,你应该使用.*?'s。

通过一些改进,该模式可能如下所示。

regpattern = "<(h[1-9]).*?id=""(.*?)"">(.*?)</\1>" 

' \1 means the same as the 1st group 
' backslash (\) is redundant to escape double quotes, so removed it 

我强烈建议你看看Repetition with Star and Plus。这是非常有用的文章,了解正则表达式中的懒惰和贪婪的重复。

哦,我差点忘了,You can't parse HTML with Regex,好吧,至少不应该。

+0

非常感谢,非常有趣的文章! – Hart

+0

@Hart并感谢您的阅读。 –