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

正则表达式求助:匹配并替换无效闭合标签的两种场景

Fixing Regex for Invalid Delimiter Pair Matching

I get it—when you have mixed correct and incorrect delimiter pairs, it's easy for regex to overmatch and capture valid content along with the invalid stuff. Let's break down how to target exactly those incorrect segments while keeping your required gsU flags.

First, let's restate your rules clearly to align:

  • Valid:
    1. Segments starting with @ must end with $@ (not just @)
    2. Segments starting with $ must end with @$ (not just $)
  • Invalid:
    1. @ ... @ (opens with @, closes with @ instead of $@)
    2. $ ... $ (opens with $, closes with $ instead of @$)

Your current regex /@(.*)\$(.*)@(.*)\$/gsU is matching too broadly because it doesn't distinguish between valid closing delimiters and invalid ones. Here's how to fix it with lookarounds to exclude valid sequences:

Regex for Invalid @ ... @ Segments

/@(?!\$)(.*?)(?<!\$)@/gsU

Breakdown:

  • @(?!\$): Matches an opening @ that isn't followed by $ (so we don't confuse it with the start of a $@ segment)
  • (.*?): Ungreedily grabs the content in between (the U flag helps here, but adding ? makes it explicit)
  • (?<!\$)@: Matches a closing @ that isn't preceded by $—this is exactly the invalid close we want to target (since valid closes are $@)
  • gsU: Keeps your required flags: g (global match), s (dotall, so . matches newlines), U (ungreedy)

When you run this on your first test line:

@Correct $tags$ before@ @these $incorrect@ tags$
It will only match the invalid part: @these $incorrect@

Regex for Invalid $ ... $ Segments

For the second scenario, use this similar pattern tailored to $ delimiters:

/\$(?!@)(.*?)(?<!@)\$/gsU

Breakdown:

  • \$(?!@): Matches an opening $ not followed by @
  • (.*?): Ungreedily captures inner content
  • (?<!@)\$: Matches a closing $ not preceded by @ (invalid, since valid closes are @$)
  • gsU: Same flags as before

Testing this on your second test line:

$Correct @tags@ before$ $these @incorrect$ tags@
It will only match the invalid segment: $these @incorrect$

Match Both Invalid Cases at Once (Optional)

If you want to catch both types of errors in one regex, combine them with alternation:

/(?:@(?!\$)(.*?)(?<!\$)@|\$(?!@)(.*?)(?<!@)\$)/gsU

Why Your Original Regex Didn't Work

Your initial pattern was capturing from the first @ to the last $ because it didn't account for valid closing delimiters. By adding negative lookbehind and lookahead, we ensure we only target the exact invalid pairs without spanning across valid content.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 15:47:59