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

Java中Regex报错\((?:[^()]|.((?R)))\)+的解决咨询

解决Java正则不支持递归匹配嵌套括号的问题

因为Java正则引擎不支持(?R)这类递归语法,要解析目标字符串,有两种可靠方案:

方案一:手动遍历计数解析(推荐,支持任意层级嵌套)

通过遍历字符串维护括号计数器,精准定位目标区间:

String input = "my params ( string(80), string(30), string(10) ) as ...";
// 定位第一个左括号和"as"的位置
int start = input.indexOf('(');
int asPos = input.indexOf(" as ");
if (start == -1 || asPos == -1 || start >= asPos) {
    // 处理无匹配的异常情况
    return;
}

int bracketCount = 1;
int end = -1;
// 从左括号后开始遍历到"as"之前
for (int i = start + 1; i < asPos; i++) {
    char c = input.charAt(i);
    if (c == '(') {
        bracketCount++;
    } else if (c == ')') {
        bracketCount--;
        // 计数器归0时,找到匹配的右括号
        if (bracketCount == 0) {
            end = i;
            break;
        }
    }
}

if (end != -1) {
    // 截取并去除首尾空格
    String targetContent = input.substring(start + 1, end).trim();
    System.out.println(targetContent); // 输出:string(80), string(30), string(10)
}

方案二:有限层级的正则匹配(适合固定嵌套深度场景)

如果能确定嵌套层级不会超过固定值(比如示例中仅一层嵌套),可以写对应层级的正则:

String input = "my params ( string(80), string(30), string(10) ) as ...";
// 匹配最多一层嵌套的括号,且后面紧跟" as "
Pattern pattern = Pattern.compile("\\((?:[^()]|\\([^()]*\\))*\\)(?=\\s+as)");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
    String match = matcher.group();
    String targetContent = match.substring(1, match.length() - 1).trim();
    System.out.println(targetContent);
}

如果需要支持更深层级,只需扩展正则中的嵌套部分,比如支持两层嵌套可写成:\\((?:[^()]|\\((?:[^()]|\\([^()]*\\))*\\))*\\)(?=\\s+as),但层级过多会导致正则过于冗长,不如手动解析灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:00:17