In my current work, i have been writing a lot of test in Java, which obviously means i need to learn a lot more about the Java api, which is good i think?????
Well i needed to match the single digit in this string "home-area-1" and return this digit. With a quick google i found this piece of code here.
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
System.out.println(b);
A quick run of this code printed "true" which means the code works.
So i wrote this:
Pattern p = Pattern.compile("[1,2,3,4]");
Matcher m = p.matcher("promo-area-3");
System.out.println(m.group());
and guess what this fails ...... giving me an "illegal state exception"
Pattern p = Pattern.compile("[1,2,3,4]");
Matcher m = p.matcher("promo-area-3");
boolean b = m.matches();
System.out.println(b);
This returns false which suggests that matching is not working properly.
After a lot of guesses and try and errors , i did
Pattern p = Pattern.compile("[1,2,3,4]");
Matcher m = p.matcher("promo-area-3");
while (m.find()) {
System.out.println("regex stuff " + m.group());
}
My thinking is this, the first code with this pattern "Pattern.compile("a*b");" was searching for a text which the subsequent one "Pattern.compile("[1,2,3,4]")" was a search for a character within a sequence and maybe this account for the while loop with m.find ........
Am not sure, maybe if anyone has a better explanation ... i would appreciate
No comments:
Post a Comment