如何使用正则表达式仅匹配 <h></h> 标签之间的标题,而不返回标签本身?

How to match only the titles between <h></h> tags, without returning the tags themselves, using regular expressions?

提问人:hengxin 提问时间:3/10/2023 最后编辑:Andy Lesterhengxin 更新时间:3/10/2023 访问量:36

问:

我想使用正则表达式将 HTML 文件中的标题匹配到 ,而不返回标签本身。h1h6h

请考虑以下 HTML 文件。 我想匹配“欢迎来到我的主页”、“SQL”、“正则表达式”,但不匹配“这不是有效的 HTML”(它被一对不匹配的标签包围)。

<body>
  <H1>Welcome to my Homepage</H1>
  Content is divided into two sections:<br/>
  <h2>SQL</h2>
  Information about SQL.
  <h2>RegEx</h2>
  Information about Regular Expressions.
  <h3>This is not a valid HTML</h4>
</body>

我使用(?<=<[hH]([1-6])>).*?(?=<\/[hH]\1>) 在 regex101.com。但是,它也会对标签中的数字 和 进行数学计算。12<H1><h2>

如何解决?

html 解析 正则表达 -lookarounds 非贪婪

评论


答:

1赞 Bergi 3/10/2023 #1

它还匹配标签中的数字 和 。12<H1><h2>

没有。匹配项本身仅捕获内容。该数字来自您后视中的捕获组。你可以忽略它。