加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用[a-z]正则表达式在Java中拆分String

发布时间:2020-12-13 21:52:59 所属栏目:百科 来源:网络整理
导读:我有两个 regexpressions: [a-c] : any character from a-c[a-z] : any character from a-z 并测试: public static void main(String[] args) { String s = "abcde"; String[] arr1 = s.split("[a-c]"); String[] arr2 = s.split("[a-z]"); System.out.pri
我有两个 regexpressions:
[a-c] : any character from a-c

[a-z] : any character from a-z

并测试:

public static void main(String[] args) {
    String s = "abcde";
    String[] arr1 = s.split("[a-c]");
    String[] arr2 = s.split("[a-z]");

    System.out.println(arr1.length); //prints 4 : "","","de"
    System.out.println(arr2.length); //prints 0 
}

为什么第二次分裂表现得像这样?我希望有一个带有6个空字符串“”结果的reslut.

根据 the documentation of the single-argument String.split

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

要保留尾随字符串,可以使用双参数版本,并指定负限制:

String s = "abcde";
    String[] arr1 = s.split("[a-c]",-1); // ["","de"]
    String[] arr2 = s.split("[a-z]",""]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读