• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

java regex

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hay,
this code gives Runtime Exception called IllegalStateException.
but if I change expresion "ab" in to "\\d" it compiles fine .

what is the reason can any body explain this ...

my problem is why we don't get same Exception at Second time


import java.util.regex.*;

class Ze{
public static void main(String s[]){

Pattern a=Pattern.compile("ab");
Matcher m=a.matcher("ababab");


while(m.find()){
m.find();m.find();m.find();
System.out.println(m.start()+m.group());
}



}
}
 
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Its thorwing IllegalStateException because when you are calling m.find() 4 times (once in while condition and inside loop 3 times) and the last m.find() call will result in false. When you invoke m.start() and m.group() when the find() method returns false, it will throw IllegalStateException.

PLease refer to Java Docs of start() and group() methods.

Hope this helps!
[ December 01, 2008: Message edited by: M Srilatha ]
 
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
as per my knowledge....

when you are using "ab"

first three find() methods are returning true (1st one in while and 2 are in while) fourth find() returns false....

when it is executing m.state() method it is throwing IllegalStateException...

If we take "\\d"

In first attempt m.finid() returns false so it is executing while...

thats why it is not throwing any exception

Hope it is cleared.....
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic