JavaScript正则表达式中能否在前向断言内使用捕获组?
Great question! Let's unpack why your attempted regex doesn't work, and then show you how to make this approach work properly.
Why your regex /([01])+(?=[^\1]|$)/ fails
The core issue here is that backreferences like \1 don't work inside character classes ([]). When you write [^\1], the regex engine interprets \1 as the ASCII character with code point 1 (a non-printable control character), not as a reference to the value captured by group 1. So your lookahead is checking for "a character that isn't ASCII 1" instead of "a character that isn't the same as the one captured in group 1"—which is totally not what you intended.
Is this approach feasible? Absolutely!
You can absolutely achieve your goal of matching consecutive runs of 0s or 1s using a backreference in a lookahead—you just need to avoid putting the backreference inside a character class. Here's how to do it:
Working regex
/([01])\1*(?!\1)/
Breakdown:
([01]): Capture either a0or1into group 1.\1*: Match zero or more additional instances of the same character captured in group 1 (this extends the match to cover the entire consecutive run).(?!\1): Negative lookahead that ensures the next character is not the same as the one in group 1 (or we're at the end of the string, since a lookahead for nothing after the end is considered true).
Test it out
Let's run it with your example string:
'001100011101'.split(/([01])\1*(?!\1)/).filter(c => !!c)
Result:
[ '00', '11', '000', '111', '0', '1' ]
Perfect—this matches exactly the same output as your original regex, but in a more concise, DRY way.
Alternative: Positive lookahead version
If you prefer using a positive lookahead instead, you can write it like this:
/([01])+(?=(?:(?!\1).)|$)/
This works by checking that the match is followed by either:
(?:(?!\1).): Any character that isn't the same as group 1- Or
$: The end of the string
Running this with your example will give the same result as well.
Key takeaway
Backreferences are powerful, but remember they can't be used inside character classes. For logic like "match until a different character appears", use negative/positive lookaheads with backreferences outside of character classes instead.
内容的提问来源于stack exchange,提问作者statox

