You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

正则表达式反向否定预查(Negative Look-behind)实现条件匹配需求的问题咨询

Fixing Your Regex to Match Only @if(Medellin) Cases

Got it, let's sort out this regex issue for you. The problem with your current pattern (?<!@if\(null\)).*?@end$ is that the negative lookbehind only checks if the immediate left of the current position isn't @if(null)—but when your string starts with @if(null), the regex still matches the whole thing because the lookbehind doesn't account for the start of the string properly.

The Correct Regex for Your Exact Need

If you only want to extract content specifically when the condition is @if(Medellin), use this pattern:

^@if\(Medellin\)\s*(.*?)\s*@end$

Let's break down what this does:

  • ^ anchors the match to the start of the string, so we only match strings that begin with our target condition.
  • @if\(Medellin\) exactly matches the opening condition (we escape parentheses with \ because they're special regex characters).
  • \s* matches any optional whitespace between the condition and your content.
  • (.*?) is a non-greedy capture group that grabs your desired content (in this case, "City Medellin").
  • \s*@end$ matches optional whitespace followed by the closing @end, anchored to the end of the string.

How It Works With Your Test Strings

  1. For @if(Medellin) City Medellin @end:
    • The regex matches the entire string, and the capture group returns City Medellin (exactly what you want).
  2. For @if(null) City Medellin @end:
    • The regex doesn't match at all because the start of the string doesn't match @if(Medellin)—so no content is extracted, which is correct.

A More Flexible Version (If You Need It)

If you ever want to extract content for any @if(...) condition except @if(null), you can use this pattern instead:

^@if\((?!null\))[^)]+\)\s*(.*?)\s*@end$

Here, (?!null\)) is a negative lookahead that ensures the content inside @if() isn't "null", and [^)]+ matches any valid condition text.

That should solve your problem perfectly!

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

火山引擎 最新活动