拆分字符串,整数以及特殊字符(“_”)

时间:2013-04-11 08:14:46

标签: java regex

我正在尝试在字符串,整数和特殊字符之间进行分割,我尝试了一些方法,但是对我来说不起作用,所以对它有任何想法吗?

源代码:

    String a = "abc1_xyz1";

        String[] qq = a.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)|('_')");

        for(int i=0; i<qq.length; i++){
            System.out.println(qq[i] + " \n");
        }

我的期望输出是:

abc
1
_
xyz
1

但我得到的是:

abc
1
_xyz
1

这里有人可以给我指导吗?

4 个答案:

答案 0 :(得分:3)

你有几个小问题。 \ D将匹配_,您不希望在您的代码中 此外,在_上拆分会将其从输出中排除。

此代码可以使用

    String a = "abc1_xyz1";

    for (String s : a.split("" +
        "(?<=[a-z])(?=\\d)" +    // space between letter and digit
        "|(?<=\\d)(?=[a-z])" +   // space between digit and letter
        "|(?<=_)(?=\\d)" +       // space between _ and digit
        "|(?<=\\d)(?=_)" +       // space between digit and _
        "|(?<=_)(?=[a-z])" +     // space between _ and letter
        "|(?<=[a-z])(?=_)" +     // space between letter and _
        "")) {
        System.out.println(s);
    }

答案 1 :(得分:2)

我认为split()是错误的方式,因为你没有任何分隔符,并且想要使用分割的所有内容(它在值之间给出空行)。

相反,假设表达式是常规的,我会使用Pattern.compile()Matcher.group(),因此:

    String a = "abc1_xyz1";
    Pattern p = Pattern.compile("(\\D+)(\\d+)(_)(\\D+)(\\d+)");
    Matcher m = p.matcher(a);
    if (m.find()) {
        for (int i = 1; i<=m.groupCount();i++) {
            System.out.println(m.group(i));
        }
    }

如果任何组是可选的,您可以在其后面添加一个问号(然后该组将为空)。

答案 2 :(得分:1)

另一种解决方案:在检查数字/非数字边界之前检查_

String[] qq = a.split("(_)|(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");

答案 3 :(得分:0)

根据the documentation of Pattern \D是“非数字”。 _是非数字,因此会匹配。

尝试使用\D(匹配任何ASCII字母)或\p{Alpha}(匹配任何Unicode字母)替换代码中的\p{L}

相关问题