Matching Multiple Groups in a Java-Regex -


is possible find groups in regular expression match specific part of string?

    pattern pattern = pattern.compile("(green trousers)|(green\\s+t)");     matcher matcher = pattern.matcher("my beautiful green trousers red!");     while (matcher.find()) {         (int = 1; <= matcher.groupcount(); i++) {             if (matcher.group(i) != null) {                 system.out.println("group " + + " matched");             }         }     } 

this example returns first group matching, interested in fact second group matches too.

there's no direct way this, regular expression consume string left right until finds match.

using | means first check first alternative, if doesn't match backtracks , tries second alternative. in case (green trousers) matches, searching stops , match returned.


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -