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

正则表达式匹配需求:排除方括号内内容及全重复字符序列

Fixing the ABBA-Style Regex to Exclude All-Repeated Characters

Got it, let's tackle this problem. Your current regex matches ABBA-style sequences (like baab or sdds) and excludes those inside square brackets, but it's incorrectly catching all-repeated strings like bbbb because it doesn't enforce that the first two captured characters are different. Here's how to fix it:

The Modified Regex

/([a-z])([a-z])(?!\1)\2\1(?![^[]*])/

Breakdown of Changes

Let's walk through what each part does, focusing on the key fix:

  • ([a-z]): Captures the first lowercase letter into group 1.
  • ([a-z]): Captures the second lowercase letter into group 2.
  • (?!\1): This is the critical addition — it's a negative lookahead that ensures the character in group 2 is NOT the same as group 1. This immediately blocks cases where all four characters are identical (like bbbb).
  • \2\1: Matches the same characters as group 2 followed by group 1, completing the ABBA pattern.
  • (?![^[]*]): Retains your original logic to exclude sequences inside square brackets — it checks that there's no closing ] ahead without an opening [ first, ensuring the match isn't nested inside brackets.

Test Cases

  • ✅ Matches successfully: baab, sdds, xyyx, abba
  • ❌ Fails to match (as intended): bbbb (all repeated characters), [baab] (inside square brackets), abca (doesn't follow the ABBA structure)

If you need to support uppercase letters too, just adjust the character class to [a-zA-Z].

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:35:53