如何实现从右到左的非贪婪Regex匹配?提取目标子串求助
Hello to World Segment Hey there! Let's figure out how to fix this regex issue you're dealing with. The core problem here is that your current regex is grabbing the first occurrence of Hello and stretching all the way to World, but you need to target only the last Hello that precedes World—and get the shortest possible match.
The Fix: A Regex with Negative Lookahead
Here's an elegant solution that locks onto the final Hello and stops at the first World:
Hello(?!.*Hello).*?World
If your string contains line breaks, add the single-line mode flag ((?s)) to make . match newlines:
(?s)Hello(?!.*Hello).*?World
How It Works
Let's break down each part to understand why this works:
Hello: Matches the starting keyword we care about.(?!.*Hello): This is a negative lookahead assertion. It checks that after the currentHello, there are no other instances ofHelloanywhere in the rest of the string. This guarantees we're only matching the lastHellobeforeWorld..*?: The non-greedy wildcard matches any characters (except newlines, unless you use(?s)) until it hits the first occurrence ofWorld. The?ensures we don't overmatch beyond the firstWorld.World: Matches our ending keyword to complete the segment.
Testing with Your Source String
For your source text:
blablabla Hello blablablabla blablabla Hello blablabla blablabla blablabla Hello I want this to be matched World blablabla blablablablablablablablablablablabla
This regex will precisely extract:
Hello I want this to be matched World
No extra fluff from earlier Hello instances—exactly what you need.
Why Your Previous Regex Failed
If you were using something like Hello.*World (greedy) or Hello.*?World, the issue was that the regex would grab the first Hello it finds. The negative lookahead in our fix eliminates that by ensuring we only pick the final Hello before World.
内容的提问来源于stack exchange,提问作者Klaus Valse

