使用.replaceAll和.split在Java中使用正则表达式

时间:2013-03-25 17:31:17

标签: java regex

我想知道我必须使用哪个正则表达式。方法中的代码是:

while( (line = bReader.readLine()) != null){
    line2 = line.replaceAll("[\\)][\\|]","R");
    numbers = line2.split("[\\|]");
}
int num = numbers.length;

我想要的是当line等于

(A#,A#,A#),(B#,B#,C#),(B#,B#,C#),(Bb,Bb,Cb)|(Ab,Ab,Ab),(Bb,Bb,Cb),(Bb,Bb,Cb),(Bb,Bb,Cb)|

必须返回num = 0,因为)|的所有实例都被R替换,并且没有|。我得到的是num = 1

line等于

(A#,A#,A#),(B#,B#,C#),(B#,B#,C#),(Bb,Bb,Cb)|A#,B#,C#,D#, E#,F#,G#,  |  ,A,  , ,   ,  ,  ,  ,  ,  ,  , ,   ,  ,  ,  |

必须返回num = 2,因为在|替换)|之后有两个R个实例。我得到的确是num = 2。我希望有人能给我解决方案。

2 个答案:

答案 0 :(得分:1)

如果您要查找String中存在多少|个未由)预测的标记,则可以删除这些标记并检查字符串的长度是如何更改的。要检测此类管道,您可以使用negative look-behind

int num = s.length() - s.replaceAll("(?<![)])[|]", "").length();

答案 1 :(得分:0)

如果您在不存在的分隔符上拆分String,那么您将返回原始String

public static void main(String[] args) throws SQLException {
    System.out.println(Arrays.toString("My string without pipes".split("\\|")));
}

输出:

[My string without pipes]

如果您尝试拆分字符串以字符串结尾的字符请勿String中获取空Array

public static void main(String[] args) throws SQLException {
    System.out.println(Arrays.toString("My string ending in pipe|".split("\\|")));
}

输出:

[My string ending in pipe]

所有发生的事情都是最后的分隔符被删除。

所以你的逻辑错了。你在第二次检查中得到正确答案的原因不是因为检查是正确的,而是因为管道恰好在最后。

一般情况下,使用String,您无法获得spilt中的分隔符数量,除非+1以分隔符开头或结尾,否则您将获得String数字 - 在这种情况下,它将被简单地删除。

您需要做的是使用正则表达式搜索不在右括号前面的所有管道。你可以用负面的背后隐藏来做到这一点:

public static void main(String[] args) throws SQLException {
    final String s1 = "(A#,A#,A#),(B#,B#,C#),(B#,B#,C#),(Bb,Bb,Cb)|(Ab,Ab,Ab),(Bb,Bb,Cb),(Bb,Bb,Cb),(Bb,Bb,Cb)|";
    final String s2 = "(A#,A#,A#),(B#,B#,C#),(B#,B#,C#),(Bb,Bb,Cb)|A#,B#,C#,D#, E#,F#,G#,  |  ,A,  , ,   ,  ,  ,  ,  ,  ,  , ,   ,  ,  ,  |";
    final Pattern pattern = Pattern.compile("(?<!\\))\\|");
    int count = 0;
    final Matcher matcher = pattern.matcher(s1);
    while (matcher.find()) {
        ++count;
    }
    System.out.println(count);
    count = 0;
    matcher.reset(s2);
    while (matcher.find()) {
        ++count;
    }
    System.out.println(count);
}

输出:

0
2