You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写正则表达式匹配后续紧跟<snippet>标签的<name>标签内容

Fixing the Regex to Match Tags Followed by

Your current regex is close, but it’s too rigid about the whitespace between </name> and <snippet>—plus it doesn’t properly exclude the first <name> tag because it doesn’t flexibly validate what comes right after the closing </name>. Let’s adjust it to handle this correctly.

The Corrected Regex

<name>([\s\S]*?)<\/name>(?=\s*<snippet>)

Breakdown of the Changes

  • <name>([\s\S]*?)<\/name>: This part still matches the <name> tag and its content using non-greedy matching (*?) to avoid accidentally spanning multiple tags. The parentheses capture the inner text of the <name> tag if you need to extract it later.
  • (?=\s*<snippet>): This is a positive lookahead assertion—it checks that immediately after the closing </name> tag, there are zero or more whitespace characters (\s*, which includes newlines, spaces, and tabs) followed by a <snippet> tag. This ensures we only match <name> tags that are directly followed by <snippet>, regardless of how much whitespace sits between them.

How It Works for Your XML

In your sample XML:

  • It will match <name>kml_2</name> and <name>kml_4</name> because both are followed by <snippet> (with possible whitespace in between).
  • It will not match <name>title</name> because after its closing tag comes <visibility> instead of <snippet>.

If you need to include the exact <snippet> </snippet> content (like your original regex did), you can adjust it to:

<name>([\s\S]*?)<\/name>\s*<snippet> </snippet>

The \s* replaces the literal [\r\n] to handle any whitespace (not just a single newline), which makes it more robust.

内容的提问来源于stack exchange,提问作者Mario

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:27:39