如何编写正则表达式匹配后续紧跟<snippet>标签的<name>标签内容
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
相关产品推荐
相关产品推荐

