有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用java编写正则表达式。使用字符串。split()方法。我希望它在第一次出现“(”之后停止分裂

我有这样格式的字符串:“a,b,c,d”和这样的格式:“a(b,c,d)” 我想在“,”或“,”上拆分,但当我遇到第二种格式中的“(”时,我想终止拆分。 这就是我开始黑客攻击之前的情况

String [] stringArray = string.split(", |,");

第一种格式的数组将包含:“a”、“b”、“c”、“d” 第二种格式的数组将包含“a(b,c,d)”

例如:

String string1 = "ab,cd, de";
String string2 = "ab(de,ef);
String [] array1 = string1.split(...);
String [] array2 = string2.split(...);

array1 result: ["ab" "cd" "de"]
array2 result: ["ab(de,ef)"]

逗号之间的字符数不受限制。我希望这更清楚

谢谢


共 (3) 个答案

  1. # 1 楼答案

    如果您知道括号始终是正确平衡的,并且它们永远不会嵌套在其他括号中,那么这将起作用:

    String[] result = source.split(",\\s*(?![^()]*\\))");
    

    如果先行查找发现一个)而没有首先看到一个(,那么它必须在一对paren中。给定此字符串:

    "ab,cd, de,ef(gh,ij), kl,mn"
    

    result将是:

    ["ab", "cd", "de", "ef(gh,ij)", "kl", "mn"]
    
  2. # 2 楼答案

    我认为你需要的是一个消极的回顾;根据文档,Java正则表达式类似于(或多或少)Perl正则表达式;但是,在Perl中没有实现可变长度的lookbehind,因此(?<!\(.*),\s*将不起作用(它将匹配逗号后跟任意数量的空格或不带空格,并且前面不带(后跟任何内容,也就是说,仅当前面不带(时才匹配逗号)

    我认为最简单的方法是在第一个(出现时分割(您可以避免regex这样做),并以不同的方式处理两个结果段,在,上分割第一个段,并将第二个段添加到最后一个数组中(前面有可能丢失的(

    编辑

    由于“a(b,d)”应该给出“a(b,d)”,因此必须将((包括)之后的任何内容附加到“first”段中最后一个拆分的字符串。然而,这个概念和以前写的一样

  3. # 3 楼答案

    使用indexOf()方法

    首先,检查字符串是否有“(”

       index = string.indexOf('(');  
    
       if(index ==-1)  // it means there is no '(' 
          {
            string.split(...);
          }
       else
          {
             subString = string.subString(0,index); // the part of the string before the '('
    
             // now do the following-
             // 1. proceed with split on substring
    
             // array1 = substring.split(...)
    
             // 2. Create a new array, insert the elements of array1 in it,
             // followed by the remaining part of the string
    
             // array2 = combine(array1, string.subString(index+1)); // <  you will need to write this method   
          }