如何使用JavaScript正则表达式匹配仅包裹在双花括号中的文本(包含括号本身)
Got it, I see the problem with your current regex! The /{{([^}]+)}}/g works great for standard double-brace cases, but when you hit triple braces (like {{{Text}}}), it messes up because [^}]+ doesn't care if there's an extra { inside the match—it just grabs everything until the first }. Let's fix this with lookaround assertions to make sure we only match exactly double braces, no more, no less.
The Updated Regex
/(?<!{){{((?:(?!}}).)+)}}(?!})/g
Let's Break This Down
Here's why this fixes your issue:
(?<!{): This is a negative lookbehind—it checks that the{{isn't immediately preceded by another{. So it won't accidentally match the first two braces in a{{{sequence.{{: Just matches the opening double braces, plain and simple.((?:(?!}}).)+): Instead of using[^}]+(which stops at any single}), this part matches any character except when it's the start of a closing}}pair. That means if you have a single}inside your content (like{{Hello}World}}), it will still match the whole thing instead of cutting off early.}}: Matches the closing double braces exactly.(?!}): A negative lookahead that makes sure the}}isn't followed by another}. So it won't match the last two braces in a}}}sequence.
Test It Out
- For your example
{ {{Text}} }, this regex will perfectly target{{Text}}—the spaces around the braces don't trigger the lookaround checks, which only care about adjacent{or}characters. - If you have something like
{{{TripleStart}}}or{{TripleEnd}}}, it won't match anything at all—those extra braces get blocked by the lookbehind/lookahead. - Even trickier cases like
{{This has a single } inside}}work correctly, since the regex doesn't stop at the first}.
Why Your Original Regex Was Acting Up
The [^}]+ in your original regex matches any character that isn't a }, so when it sees {{{Text}}}, it grabs the third { along with Text (since { isn't a }), then pairs that with the first two closing }. That's why you ended up with a match that included the extra opening brace and missed the last one—this new regex fixes that by enforcing strict double-brace boundaries.
内容的提问来源于stack exchange,提问作者jonnoMK




