• Post Reply Bookmark Topic Watch Topic
  • New Topic

matcher.matches()  RSS feed

 
Garrett Smith
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone explain this?

[Garrett-Smiths-Computer:~/Documents/java/patterns] garrett% java Patterns
Exception in thread "main" java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Matcher.java:353)
at Patterns.main(Patterns.java:54)


[Garrett-Smiths-Computer:~/Documents/java/patterns] garrett% java Patterns
1x
Unless I call m.matches, the pattern fails. Why? Is this a bug?
[ January 18, 2003: Message edited by: Garrett Smith ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, this is normal behavior. A Matcher does not automatically try to match a given pattern until you call either matches() or find() - because it does not know in advance whether you want it to match the entire input at once (as for matches()) or just look for a match somewhere within the input (as for find()). Thus, you must call either matches() or find() (and check that the return value is true) before trying to use group(int).
 
Garrett Smith
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Since no previous match exists, then the IllegalStateException is thrown.
matches() tries to match a pattern, thereby changing the state of the matcher.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!