regex - Java: Regular expression doesn't work as expected -


i have following piece of code:

string range = "(15-42)"; string regexp = "(\\d{1,})(\\d{1,})";  pattern p = pattern.compile(regexp); matcher m = p.matcher(range);  m.find();  system.out.println(m.groupcount());  for(int i=0; i<=m.groupcount(); i++){ system.out.println("value:" + m.group()); } 

and have following output:

2 value: 15 value: 1 value: 5 

but i'm expecting see 2 values: 15 , 42.

why doesn't work expected?

you need add hyphen regex , use .group(i) , start index 1 (because m.group(0) whole match value not need):

string range = "(15-42)"; string regexp = "(\\d{1,})-(\\d{1,})"; pattern p = pattern.compile(regexp); matcher m = p.matcher(range); if (m.find()) {     system.out.println(m.groupcount());     for(int i=1; i<=m.groupcount(); i++){         system.out.println("value:" + m.group(i));     } } 

see ideone demo

now, have

2               // number of capturing groups value:15        // value of first capturing group value:42        // value of second capturing group 

Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -