Identifying capture groups in a Regex Pattern

佐手、 提交于 2019-12-10 15:46:33

问题


Is there a way in Java (perhaps with an additional Open Source library) to identify the capture groups in a java.util.regex.Pattern (i.e. before creating a Matcher)

Example from the Java docs:

Capturing groups are numbered by 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 it should be possible to identify these from the (compiled) Pattern.

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


回答1:


You can find out the number of groups by creating a dummy Matcher, like so:

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

If you want the actual subexpressions (((A)(B(C))), (A), etc.), then no, that information is not available.




回答2:


Yes. Check this:

Regex Named Groups in Java



来源:https://stackoverflow.com/questions/4589643/identifying-capture-groups-in-a-regex-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!