java - regex to match and retrieve some tokens -
the strings interested in followings a1.foo
, a2.bar
, a3.whatever
now need retrieve number. wrote piece of code (in java), thinking work, not. please let me know wrong 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 expected print 2
your regex wrong ([^\\w])
match 1 non-word character. wanted more 1 word character hence (\\w+)
however can use lookahead:
pattern.compile("a(\\d*)(?=\\.)");
Comments
Post a Comment