[英]regex in Java with .replaceAll and .split
我想知道我必须使用哪个正则表达式。 方法中的代码是:
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
。 我希望有人能给我解决方案。
如果您想找出多少|
标志着不由预测字符串存在)
那么你可以删除这些标记,并检查字符串的长度如何变化。 要检测此类管道,可以使用负向后看 。
int num = s.length() - s.replaceAll("(?<![)])[|]", "").length();
如果您在不存在的定界符上分割String
,则将获得原始的String
:
public static void main(String[] args) throws SQLException {
System.out.println(Arrays.toString("My string without pipes".split("\\|")));
}
输出:
[My string without pipes]
如果尝试分割以字符串结尾的字符,则在Array
不会得到空String
:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.