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

如何编写正则表达式按逗号分割字符串,忽略<>内(含嵌套)的逗号?

仅分割尖括号外逗号的实现方案

你的需求是分割字符串时,仅在尖括号<>外部的逗号处拆分,同时支持尖括号多层嵌套的场景。你之前使用的正则,(?![^<>]*\))存在两个问题:一是错误地将闭合符号写成了)而非>,二是无法处理多层嵌套结构——[^<>]*只能匹配到第一个>,嵌套内部的结构会被忽略,导致分割错误。

以下是两种可靠的解决方案:

方案一:手动遍历字符分割(推荐)

Java原生正则不支持处理嵌套结构的平衡匹配,手动遍历计数尖括号层级的方式逻辑清晰、稳定性强:

  • 初始化层级计数器depth,初始值为0
  • 遍历字符串每个字符:
    • 遇到<时,层级加1
    • 遇到>时,层级减1(需确保层级不小于0,避免非法格式)
    • 遇到逗号且层级为0时,此处为有效分割点
  • 根据分割点截取子串,收集结果

代码示例

import java.util.ArrayList;
import java.util.List;

public class StringSplitUtil {
    public static List<String> splitOutsideAngleBrackets(String input) {
        List<String> result = new ArrayList<>();
        int startIndex = 0;
        int bracketDepth = 0;

        for (int i = 0; i < input.length(); i++) {
            char currentChar = input.charAt(i);
            switch (currentChar) {
                case '<':
                    bracketDepth++;
                    break;
                case '>':
                    if (bracketDepth > 0) {
                        bracketDepth--;
                    }
                    // 可添加非法格式的处理逻辑,比如抛出异常
                    break;
                case ',':
                    if (bracketDepth == 0) {
                        result.add(input.substring(startIndex, i).trim());
                        startIndex = i + 1;
                    }
                    break;
            }
        }
        // 添加最后一段内容
        if (startIndex < input.length()) {
            result.add(input.substring(startIndex).trim());
        }
        return result;
    }

    public static void main(String[] args) {
        String testStr = "contentType:string,header:string,alternativeIds:array<struct<id:int,name:string>>, flag:boolean";
        List<String> splitResult = splitOutsideAngleBrackets(testStr);
        splitResult.forEach(System.out::println);
    }
}

运行输出

contentType:string
header:string
alternativeIds:array<struct<id:int,name:string>>
flag:boolean

方案二:第三方正则库(不推荐)

Java原生正则不支持平衡组语法,若一定要用正则实现,需依赖支持平衡组的第三方库(如JRegex),但这种方式需要额外引入依赖,且不如手动遍历直观,仅在特殊场景下考虑使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 13:18:04