如何确保正则表达式在调用时始终匹配

When working with Matcher objects, I've noticed that trying to retrieve the results of a Pattern match often results in a java.lang.IllegalStateException: No successful match so far.

例如,给出以下代码:

Pattern pobj = Pattern.compile("\b([1]?\\d) ([AP]M)");
Matcher mobj = pobj.matcher(some_string);

尝试执行:

mobj.group(1)

结果是:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.xxxx.xxxx, PID: xxxxx
    java.lang.RuntimeException: Unable to start receiver com.xxx.xxx.xxx: java.lang.IllegalStateException: No successful match so far
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:3814)
        at android.app.ActivityThread.-wrap18(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2082)
        at android.os.Handler.dispatchMessage(Handler.java:108)
        at android.os.Looper.loop(Looper.java:166)
        at android.app.ActivityThread.main(ActivityThread.java:7529)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)

后跟一些特定于应用程序的错误文本。

但是,要检查的数据将始终与模式匹配(因为正则表达式基于数据),这意味着匹配将始终存在。我如何确保在尝试检索正则表达式结果时找到匹配项?

请注意,我知道还有其他从字符串获取信息的方法,但是我想知道如何解决此特定问题,即使我最终没有使用此方法也是如此。

评论