嗨,我最近正在开发一个代码,我必须提取最后 3 组数字。所以我使用模式来提取数据。但我没能理解。谁能帮我理解一下吗??
String str ="EGLA 0F 020";
String def = "ALT 1F 001 TO ALT 1F 029";
String arr[] = def.split("TO");
String str2 = arr[0];
System.out.println("str2:"+str2);
Pattern pt = Pattern.compile("[0-9][0-9][0-9]$");
Matcher m1 = pt.matcher(str);
Matcher m2 = pt.matcher(str2);
boolean flag = m1.find();
boolean flag2 = m2.find();
if(flag)
System.out.println("first match:::"+m1.group(0));
else
System.out.println("Not found");
if(flag2)
System.out.println("first match:::"+m2.group(0));
else
System.out.println("Not found");
上述代码产生的输出如下:::
str2:ALT 1F 001
first match:::020
Not found
请回复我卡在这里吗?
最佳答案
这是因为当你拆分时,你有一个尾随空格。
String str = "EGLA 0F 020";
String str2 = "ALT 1F 001 ";
// ^ trailing space
您可以通过多种方式修复它。例如:
- 通过拆分
“TO”
- 修剪结果
- 允许在正则表达式中添加尾随空格。
例如,此更改将起作用:
String arr[] = def.split(" TO ");
关于java - 为什么 Matcher 对于 Java 运行时获取或提供的字符串失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7794543/