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

JavaScript正则表达式无效组错误原因及替代方案咨询

Fixing the Invalid Regex Group Error in JavaScript

Hey there! Let's break down why your regex is throwing that "invalid group" error and how to fix it.

The Root Problem

Your original regex uses a negative lookbehind ((?<!\\)), which older JavaScript environments (pre-ES2018) don't support. That's exactly what's causing the invalid group error. The goal of that lookbehind was to ensure the ( we're targeting isn't escaped—meaning there are an even number of backslashes (including zero) before it.

The Alternative Solution

Instead of relying on lookbehinds, we can rewrite the regex to explicitly match valid "un-escaped" parentheses by checking for even numbers of backslashes. Here's the working version:

const regExp = /(^|[^\\](?:\\{2})*)\(([5-9]|[1-9]\d)/gi;

Let's break down what each part does:

  • (^|[^\\]): Matches either the start of the string, or any character that isn't a backslash (this ensures we don't start counting from an odd backslash)
  • (?:\\{2})*: Matches 0 or more pairs of backslashes (so even total: 0, 2, 4, etc.)
  • \(: The un-escaped left parenthesis we want to target
  • ([5-9]|[1-9]\d): Captures your target numbers (5-9, or 10 and above)

How to Use It

Since this regex captures an extra group (the leading valid character/start of string), you'll want to grab the second capture group to get just the number:

const testString = "Check (5), \\(10) (escaped, won't match), (15), and \\\\(20) (double escaped, will match)";
let match;

while ((match = regExp.exec(testString)) !== null) {
  console.log("Found valid number:", match[2]);
}
// Output:
// Found valid number: 5
// Found valid number: 15
// Found valid number: 20

Bonus: ES2018+ Support

If you're working in a modern environment that supports ES2018 or later, you can use the lookbehind syntax directly—just make sure your string escaping is correct:

const regExp = /(?<!\\)(?:\\{2})*\(([5-9]|[1-9]\d)/gi;

This works because modern JS engines (like Chrome, Firefox, Node.js 10+) now support lookbehind assertions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:39:26