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
Post a Comment