问题
I'm doing a pattern match in a piece of code that works fine in one circumstance but not another. The code is currently:
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");
}
}
The code throws IllegalStateException on the Dmatch.group(0) line. The output of the logcat line from the catch is "01 Jan 01 60.9876 1234" as above.
Doing a hexdump on the data file I'm reading in shows the spaces are spaces as expected and no stray characters before or after the text I'm matching. Any suggestions on debugging this?
I've done a bit of a code change just to test my expression itself, and now I'm more confused. Within the loop, I'm now checking to see if the string matches the pattern first, then running it through the compiled version:
Pattern P = Pattern.compile(DLVRYrxStr);
if(!DATAstr.matches(DLVRYrxStr)) {
Log.e(TAG, "[" + DATAstr + "] doesn't match regex");
break;
}
Matcher Dmatch = P.matcher(DATAstr);
Unfortunately(?) the pattern does match, and thus falls through to the P.matcher line, the line after which throws an exception when I try to read the first matching group:
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)
Solution is to add ".matches()" check as below:
Matcher Dmatch = DLVRYrx.matcher(DATAstr);
Dmatch.matches();
String data1 = Dmatch.group(0);
Yes, I'm using that in an 'if' statement in my code, but leaving it free-hanging as above works fine.
回答1:
Your DLVRYrx.matcher(...).groupCount() is simply telling you that there are 3 matching groups in the pattern it was created from.
i.e.
(\\d+\\s\\p{Letter}+\\s\\d+),
(\\d+(?:\\.\\d+) and
(\\d+)
You need to call either
matcher.matches()
matcher.lookingAt()
or
matcher.find()
Prior to attempting to get matcher.group(0) since these methods prompt java to parse the string.
来源:https://stackoverflow.com/questions/9893875/debugging-pattern-regex-failure-in-in-java-android