当 HTML 格式因情况而异时,您如何使用 RegEx 从 HTML 标签中检索信息?

How do you use RegEx to retrieve information from HTML tags when the HTML format differs from case to case?

所以我从 https://www.merriam-webster.com/thesaurus 中抓取各种页面以获取各种单词,然后使用 RegEx 解析出每个单词的几个上下文定义。我 运行 遇到了一个问题,即不同的词具有不同的页面格式化方式,因此我无法获得一个正则表达式来涵盖所有可能的情况。这里有两个例子。

https://regex101.com/r/mV4yH4/15https://regex101.com/r/mV4yH4/16

两个示例都使用基本相同的 RegEx,但我必须交换两个捕获组的 * 和 Greedy/Lazy 顺序。这两个不同的示例使用来自两个不同单词的数据。您会注意到,如果您对两个词使用相同的正则表达式,在一种情况下,正则表达式将匹配 HTML 的一大块而不是一部分。

这两个示例使用与上面两个示例相同的两个不同的测试字符串,但使用相同的正则表达式,您将看到它如何提取超出必要的内容:

https://regex101.com/r/mV4yH4/17https://regex101.com/r/mV4yH4/16

我不确定如何进一步优化正则表达式以在所有情况下只提取定义。该网站还可以使用其他几种格式,但为了问题和示例,我只使用了两种不同的格式。稍后我可以将此解决方案转换为其他格式。

非常感谢任何指导,非常感谢。

我修改了你的first regular expression,现在可以使用了:

  1. advertising
  2. About

备注

# uncalled for matching of opening of span.thes-list
# matching only on character in the second part of the regular expression
<span class="dt ">(.*?)<\/span> <span class="thes-list sim-list">|<span class="dt ">(.?)<ul class="vis"><li><span class="t">

更新版本

# matches only the content of the span (first part)
# added \s as to remove whitespace characters
# added quantifier to the second part +? match as much as possible non greedy
<span class="dt ">\s+(.+?)\s*<\/span>|<span class="dt ">\s+(.+?)\s*<ul class="vis"><li><span class="t">

第二次编辑

# matches only the description
<span class="dt ">\s+([^<]+?)\s+<

I'm having trouble getting a single Regular Expression to cover all the possible cases.

那是因为编写一个正则表达式来涵盖所有可能的情况是不可行的。

要可靠地解析 HTML,您需要使用 HTML 解析器。您还没有说您使用的是什么语言,但是 http://htmlparsing.com/ 可以给您一些起点。