simple java regex throwing illegalstateexception [duplicate]

余生长醉 提交于 2019-11-26 21:06:46

You need to invoke m.find() or m.matches() first to be able to use m.group.

  • find can be used to find each substring that matches your pattern (used mainly in situations where there is more than one match)
  • matches will check if entire string matches your pattern so you wont even need to add ^ and $ in your pattern.

We can also use m.lookingAt() but for now lets skip its description (you can read it in documentation).

Use Matcher#matches or Matcher#find prior to invoking Matcher.group(int)

if (m.find()) {
   System.out.println("group 1: " +m.group(1));
}

In this case Matcher#find is more appropriate as Matcher#matches matches the complete String (making the anchor characters redundant in the matching expression)

Look at the javadocs for Matcher. You will see that "attempting to query any part of it before a successful match will cause an IllegalStateException to be thrown".

Wrap your group(1) call with if (matcher.find()) {} to resolve this problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!