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

如何实现从右到左的非贪婪Regex匹配?提取目标子串求助

Solution to Extract the Last 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 current Hello, there are no other instances of Hello anywhere in the rest of the string. This guarantees we're only matching the last Hello before World.
  • .*?: The non-greedy wildcard matches any characters (except newlines, unless you use (?s)) until it hits the first occurrence of World. The ? ensures we don't overmatch beyond the first World.
  • 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:36:22