1 回答
TA贡献1796条经验 获得超7个赞
修复当前方法
您可以像这样修复您的方法:
final Pattern p = Pattern.compile( "^(?:00(?:\\s+00)*\\s+)?(\\d{2})(.*?)(\\d{2})(?:\\s+00(?:\\s+00)*)?$" );
final Matcher m = p.matcher( "00 44 88 45 00 25 78 46 00 46 58 00" );
final String first = m.replaceAll( "$1" );
final String last = m.replaceAll( "$3" );
提取方法
或者,您可以在不替换的情况下提取值:
^(?:00(?:\s+00)*\s+)?(\d{2})|(\d{2})(?:\s+00(?:\s+00)*)?$
Java演示:
String s = "00 44 88 45 00 25 78 46 00 46 58 00";
Pattern pattern = Pattern.compile("^(?:00(?:\\s+00)*\\s+)?(\\d{2})|(\\d{2})(?:\\s+00(?:\\s+00)*)?$");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
if (matcher.group(1) != null) {
System.out.println(matcher.group(1));
}
if (matcher.group(2) != null) {
System.out.println(matcher.group(2));
}
}
输出:
44
58
使用过滤方法进行拆分
此外,您可以简单地用空格拆分字符串,删除所有00项目并获取第一个和最后一个项目:
String s = "00 44 88 45 00 25 78 46 00 46 58 00";
List<String> result = Arrays.stream(s.split("\\s+"))
.filter(i -> !i.equals("00"))
.collect(Collectors.toList());
System.out.println(result.get(0)); // => 44
System.out.println(result.get(result.size()-1)); // => 58
添加回答
举报