Reputation: 23497
The strings I am interested in look like something like the followings
a1.foo
, a2.bar
, a3.whatever
Now I need to retrieve the number. So I wrote this piece of code (in Java), thinking it would work, but it does not. Could anyone please let me know what is wrong with my pattern?
final String testInput = "a2.foo";
Pattern p = Pattern.compile("a(\\d*)\\.([^\\w])");
Matcher matcher = p.matcher(testInput);
if (matcher.find())
{
System.out.println("n = " + matcher.group(1));
}
else
{
System.out.println("NOT MATCHED");
}
This prints NOT MATCHED
, while I expected it to print 2
Upvotes: 1
Views: 109
Reputation: 784898
Your regex is wrong as ([^\\w])
will match only one non-word character. You probably wanted more than 1 word character hence (\\w+)
However you can use this lookahead:
Pattern.compile("a(\\d*)(?=\\.)");
Upvotes: 2