【问题标题】:Java Array Hole Using Regex使用正则表达式的 Java 数组空洞
【发布时间】:2012-04-14 18:32:31
【问题描述】:

谁能告诉我为什么这段代码在:array[0][4] 处有一个洞?

public class Random{ 

    public static void main (String []args){

        String [][] array={{"This is a test. A hole here"}};

        for(int i=0;i<array.length;i++){
            String temp=array[i][0];

            array[i]=temp.split("[\\:., ]");
        }

        System.out.print(array[0][4]);
    }
}

然而,当我在分隔符中添加一个加号时(“[\:., ]+”),我得到了正确的输出。

public class Random{ 

    public static void main (String []args){

        String [][] array={{"This is a test. A hole here"}};

        for(int i=0;i<array.length;i++){
            String temp=array[i][0];
            array[i]=temp.split("[\\:., ]+");
        }

        System.out.print(array[0][4]);
    }
}

加号去掉这个洞并解决这个问题有什么原因吗?我愿意接受任何建议或 cmets。是的,我是新手。

【问题讨论】:

    标签: java regex arrays delimiter


    【解决方案1】:

    使用array[i]=temp.split("[\\:., ]");,您的字符串将在此处拆分:

    This is a test. A hole here
        ^  ^ ^    ^^ ^    ^
    

    所以你在array[4] 得到一个空字符串。

    array[i]=temp.split("[\\:., ]+"); 会将“.”组合成一个“分割点”,因此不会在两者之间分割。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-23
      • 2012-01-17
      • 1970-01-01
      • 2015-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多