mik*_*ock 2 java regex debugging android pattern-matching
我正在用一段代码进行模式匹配,这种代码在一种情况下可以正常工作,而在另一种情况下却不能。该代码当前为:
DLVRYrx = Pattern.compile("(\\d+\\s\\p{Letter}+\\s\\d+)\\s(\\d+(?:\\.\\d+)?)\\s(\\d+)");
Log.d(TAG, "* Regex matched " + DLVRYrx.matcher("01 Jan 01 60.9876 1234").groupCount() + " groups"); // prints 3 as expected in logcat
for (int i=19; i<(fields-6); i++) {
final String DATAstr = values[i];
try {
Matcher Dmatch = DLVRYrx.matcher(DATAstr);
String data1 = Dmatch.group(0);
} catch (IllegalStateException e) {
Log.e(TAG, "! Text ["+DATAstr+"] didn't match regex");
}
}
Run Code Online (Sandbox Code Playgroud)
该代码在Dmatch.group(0)行上引发IllegalStateException。捕获的logcat行的输出如上,为“ 01 Jan 01 60.9876 1234”。
在我正在读取的数据文件上进行十六进制转储,显示空格是预期的空格,并且在我匹配的文本之前或之后没有任何乱码。有任何调试建议吗?
我已经做了一些代码更改,只是为了测试表达式本身,现在我更加困惑了。在循环中,我现在要检查字符串是否首先与模式匹配,然后在编译版本中运行它:
Pattern P = Pattern.compile(DLVRYrxStr);
if(!DATAstr.matches(DLVRYrxStr)) {
Log.e(TAG, "[" + DATAstr + "] doesn't match regex");
break;
}
Matcher Dmatch = P.matcher(DATAstr);
Run Code Online (Sandbox Code Playgroud)
不幸的是(?)模式确实匹配,因此落入P.matcher行,当我尝试读取第一个匹配组时,此行将引发异常:
W/System.err( 1238): java.lang.IllegalStateException: No successful match so far
W/System.err( 1238): at java.util.regex.Matcher.ensureMatch(Matcher.java:607)
W/System.err( 1238): at java.util.regex.Matcher.group(Matcher.java:358)
Run Code Online (Sandbox Code Playgroud)
解决方案是添加“ .matches()”检查,如下所示:
Matcher Dmatch = DLVRYrx.matcher(DATAstr);
Dmatch.matches();
String data1 = Dmatch.group(0);
Run Code Online (Sandbox Code Playgroud)
是的,我在代码的'if'语句中使用了它,但如上所述将其自由悬挂可以很好地工作。
您DLVRYrx.matcher(...).groupCount()
只是在告诉您在其创建模式中有3个匹配的组。
即
(\\d+\\s\\p{Letter}+\\s\\d+)
,
(\\d+(?:\\.\\d+)
与
(\\d+)
您需要打电话给
matcher.matches()
matcher.lookingAt()
要么
matcher.find()
在尝试获取之前,matcher.group(0)
因为这些方法提示java解析字符串。