Split a String based on regex

后端 未结 4 874
情歌与酒
情歌与酒 2020-12-17 18:55

I have a string that needs to be split based on the occurrence of a \",\"(comma), but need to ignore any occurrence of it that comes within a pair of parentheses. For exampl

4条回答
  •  春和景丽
    2020-12-17 19:21

    Try below:

    var str = 'B2B,(A2C,AMM),(BNC,1NF),(106,A01),AAA,AX3';
    console.log(str.match(/\([^)]*\)|[A-Z\d]+/g));
    // gives you ["B2B", "(A2C,AMM)", "(BNC,1NF)", "(106,A01)", "AAA", "AX3"]
    

    Java edition:

    String str = "B2B,(A2C,AMM),(BNC,1NF),(106,A01),AAA,AX3";
    Pattern p = Pattern.compile("\\([^)]*\\)|[A-Z\\d]+");
    Matcher m = p.matcher(str);
    List matches = new ArrayList();
    while(m.find()){
        matches.add(m.group());
    }
    
    for (String val : matches) {
        System.out.println(val);
    }
    

提交回复
热议问题