Java中的调试模式(正则表达式)失败(Android)

我在一段代码中进行模式匹配,在一种情况下可以正常工作但不能在另一种情况下工作。 该代码目前是:

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"); } } 

代码在Dmatch.group(0)行上抛出IllegalStateException。 如上所述,来自捕获的logcat线的输出是“01 Jan 01 60.9876 1234”。

对我正在读入的数据文件执行hexdump显示空格是预期的空格,并且在我匹配的文本之前或之后没有杂散字符。 有关调试的建议吗?

我做了一些代码更改只是为了测试我的表达本身,现在我更加困惑。 在循环中,我现在正在检查字符串是否与模式匹配,然后在编译版本中运行:

 Pattern P = Pattern.compile(DLVRYrxStr); if(!DATAstr.matches(DLVRYrxStr)) { Log.e(TAG, "[" + DATAstr + "] doesn't match regex"); break; } Matcher Dmatch = P.matcher(DATAstr); 

不幸的是(?)模式匹配,因此落到P.matcher行,当我尝试读取第一个匹配组时,该行抛出exception:

 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) 

解决方法是添加“.matches()”检查如下:

 Matcher Dmatch = DLVRYrx.matcher(DATAstr); Dmatch.matches(); String data1 = Dmatch.group(0); 

是的,我在我的代码中的’if’语句中使用它,但是如上所述保持自由挂起工作正常。

您的DLVRYrx.matcher(...).groupCount()只是告诉您在创建它的模式中有3个匹配的组。

(\\d+\\s\\p{Letter}+\\s\\d+)(\\d+(?:\\.\\d+)(\\d+)

你需要打电话

matcher.matches()

matcher.lookingAt()

要么

matcher.find()

在尝试获取matcher.group(0)之前,因为这些方法会提示java解析字符串。