大家好!我想知道是否有人可以帮助我。
我有一个字符串-2.100 CM 1.000 CM 1.025 CM
问题是在 CM
之前获取值,例如-2.1
、1.0
、1.025
Pattern pattern = Pattern.compile("(\\-*\\d*.\\d*) CM"); would give me -2.1,
Pattern pattern = Pattern.compile(" (\\-*\\d*.\\d*) CM"); 1.0
无法获取第三个值(有没有办法根据值的出现次数获取值?
最佳答案
您可以拆分字符串。
String str = "-2.100 CM 1.000 CM 1.025 CM";
String[] array = str.split("\\s+CM\\s*");
for (String s : array) {
System.out.println(new Double(s));
}
输出:
-2.1
1.0
1.025
<小时/>
您可以尝试使用模式以及使用正向前瞻。
String str = "-2.100 CM 1.000 CM 1.025 CM";
Pattern p = Pattern.compile("[+-]?\\d+\\.?\\d*(?= CM)", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(new Double(m.group()));
}
输出:
-2.1
1.0
1.025
关于java - 根据出现次数获取子字符串,正则表达式java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25179462/