Defining capture groups in a regular expression pattern

Is there a way in Java (possibly with the optional Open Source library) to identify capture groups in java.util.regex.Pattern (i.e. before creating matches)

An example from Java docs:

Exciting groups are numbered counting their opening parentheses from left to right. In the expression ((A) (B (C))), for example, there are four such groups:

 1 ((A)(B(C))) 2 (A) 3 (B(C)) 4 (C) 

In principle, they can be identified by a template (compiled).

UPDATE: From @Leniel and eslewhere it seems that this object ("named groups") will be present in Java 7 in mid-2011. If I can't wait for this, I can use jregex, although I'm not quite sure what the API is.

+4
source share
2 answers

You can find out the number of groups by creating a dummy Matcher, for example:

 Pattern p = Pattern.compile("((A)(B(C)))"); System.out.println(p.matcher("").groupCount()); 

If you need actual subexpressions (( ((A)(B(C))) , (A) , etc.), then no, this information is not available.

+6
source
+2
source

Source: https://habr.com/ru/post/1334146/


All Articles