我会避免为此使用正则表达式。相反,我建议使用循环简单地计算尾随零的数量:
List<String> items = Arrays.asList("1000", "1200", "1300", "1310", ... );
for (String item : items) {
int count = 0;
for (int i = item.length() - 1; i >= 0 && item.charAt(i) == '0'; --i) {
count++;
}
// item has "count" trailing zeroes
}
或者,我建议使用String#endsWith()。但是使用正则表达式或使用endsWith(),因为所有以“00”结尾的字符串也以“0”结尾,所以你必须对你的测试有点聪明。因此,例如,要允许“1420”而不是“1400”,您可以使用:
if (item.endsWith("0") && !item.endsWith("00")) {
// item ends with exactly one 0
}
或者(我认为更好),您可以使用一系列if..else 条件,按尾随零长度的降序排列:
if (item.endsWith("000")) {
// item ends with (at least) three zeroes
} else if (item.endsWith("00")) {
// item ends with exactly two zeroes
} else if (item.endsWith("0")) {
// item ends with exactly one zero
} else {
// item does not end in a zero
}
如果您需要按尾随零的数量顺序输出项目,则需要将它们分类到 bin 中并在稍后的步骤中处理结果。像这样的:
List<String> one = new ArrayList<>();
List<String> two = new ArrayList<>();
List<String> three = new ArrayList<>();
for (String item : items) {
if (item.endsWith("000")) {
three.add(item);
} else if (item.endsWith("00")) {
two.add(item);
} else if (item.endsWith("0")) {
one.add(item);
}
}
// now process the results:
System.out.print("Items with one trailing zero: ");
System.out.println(String.join(", ", one);
System.out.print("Items with two trailing zeroes: ");
System.out.println(String.join(", ", two);
System.out.print("Items with three or more trailing zeroes: ");
System.out.println(String.join(", ", three);
(String#join() 方法是 Java 1.8 的新方法。如果您使用的是早期版本的 Java,则需要以不同的方式创建字符串表示。)
如果您仍然坚持使用正则表达式,您应该从匹配尾随零的Pattern 创建一个Matcher,如果找到匹配项,则检查匹配字符序列的长度:
Pattern p = new Pattern("0+$"); // match one or more trailing zeroes
for (String item : items) {
Matcher m = p.matcher(item);
if (m.find()) {
int trailingZeroCount = m.group().length();
// process accordingly
}
}