>Search for a single digit within a string using regex as provided in java api

>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

Advertisements
This entry was posted in Software Testing and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s