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

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -