【Java】关于split()函数匹配正则表达式你一定要注意的!!!

  • Post author:
  • Post category:java



问题描述:

Java中的String类中有一个方法是

split()

,可以根据指定分割符号,将源字符串分割成为一个字符串数组。



6921. 按分隔符拆分字符串

这道题目中,需要根据

.,|$#@

这些分割符号来分割源字符串,看下面的测试:

public static void main(String[] args) {
        // .,|$#@

        String word1="one.two.three";
        String separator1=".";
        String[] str1 = word1.split(separator1);
        System.out.println("one.two.three:"+str1.length);

        String word2="one,two,three";
        String separator2=",";
        String[] str2 = word2.split(separator2);
        System.out.println("one,two,three:"+str2.length);

        String word3="one|two|three";
        String separator3="|";
        String[] str3 = word3.split(separator3);
        System.out.println("one|two|three:"+str3.length);

        String word4="one$two$three";
        String separator4="$";
        String[] str4 = word4.split(separator4);
        System.out.println("one$two$three:"+str4.length);

        String word5="one#two#three";
        String separator5="#";
        String[] str5 = word5.split(separator5);
        System.out.println("one#two#three:"+str5.length);

        String word6="one@two@three";
        String separator6="@";
        String[] str6 = word6.split(separator6);
        System.out.println("one@two@three:"+str6.length);
    }
// 结果:
one.two.three:0
one,two,three:3
one|two|three:13
one$two$three:1
one#two#three:3
one@two@three3

  • 发现结果不是想象中的应该为3


问题原因:



split()

函数中传入的这个参数是作为正则表达式的。因为

. | $

是正则表达式中的元字符,而我这里是把它作为普通字符使用的。而实际传入split后

. | $

被当做元字符处理了,含义也就变了。


问题解决:

在使用

split()

函数的时候,如果要进行分割的符号为这些元字符

.$|()[{^?*+\\

,则要加上

"\\"

进行转义,否则会出现错误。

public static void main(String[] args) {
        // .,|$#@

        String word1="one.two.three";
        String separator1=".";
        String[] str1 = word1.split("\\"+separator1);
        System.out.println("one.two.three:"+str1.length);

        String word2="one,two,three";
        String separator2=",";
        String[] str2 = word2.split(separator2);
        System.out.println("one,two,three:"+str2.length);

        String word3="one|two|three";
        String separator3="|";
        String[] str3 = word3.split("\\"+separator3);
        System.out.println("one|two|three:"+str3.length);

        String word4="one$two$three";
        String separator4="$";
        String[] str4 = word4.split("\\"+separator4);
        System.out.println("one$two$three:"+str4.length);

        String word5="one#two#three";
        String separator5="#";
        String[] str5 = word5.split(separator5);
        System.out.println("one#two#three:"+str5.length);

        String word6="one@two@three";
        String separator6="@";
        String[] str6 = word6.split(separator6);
        System.out.println("one@two@three:"+str6.length);
    }
// 结果:
one.two.three:3
one,two,three:3
one|two|three:3
one$two$three:3
one#two#three:3
one@two@three3



版权声明:本文为weixin_47274607原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。