求匹配不含@href的<test>元素的正则表达式及问题解决
<test> Elements Without href Attribute Hey there! Let's sort out that regex problem you're facing. The issue with your original pattern <test\s+abc.[^href]*>.* is that [^href] is a character set, not a string exclusion. It tells the regex to exclude any single character that's h, r, e, or f—so when your abc attribute value contains any of those letters (like the h in abc_CHmnoph), the regex stops matching early, which is why your third <test> element wasn't picked up.
The Correct Regex
Here's a pattern that will reliably match all <test> elements without an href attribute:
<test\s+(?:(?!href=)[^>])+>.*?</test>
Breakdown of the Pattern
Let's break down what each part does to make it clear:
<test\s+: Matches the start of the<test>tag, followed by one or more whitespace characters (to account for attributes).(?:(?!href=)[^>])+: This is the key fix. The(?!href=)is a negative lookahead—it checks that the substringhref=does NOT start at the current position. Then[^>]matches any character that isn't a closing>, and the+repeats this logic for the entire attribute section of the tag. This ensures we only match<test>tags that never containhref=.>.*?</test>: Matches the closing>of the opening tag, then uses non-greedy.*?to capture all content inside the tag until we hit the closing</test>(this prevents over-matching if multiple tags are present).
Testing with Your Sample Content
Using your test input:
<test abc="xyz_CHCFGRc/abc_CHmnop" href="sdddzus.xml">text</test> <test abc="abc_abc">text23</test> <test abc="123_ABCc/abc_CHmnoph">text42</test>
This regex will correctly match exactly the two elements you want:
<test abc="abc_abc">text23</test><test abc="123_ABCc/abc_CHmnoph">text42</test>
Quick Note on Regex vs. HTML Parsers
While this regex works for your specific use case, it's worth mentioning that regex isn't ideal for parsing HTML in general (edge cases like nested tags or attribute values with > can break it). If you're working with more complex HTML, using a dedicated HTML parser would be more robust—but for this simple scenario, the regex above does the trick!
内容的提问来源于stack exchange,提问作者Shil

