问题描述
Java中是否有一种方法(也许带有附加的开源库)来标识 java.util.regex.Pattern
中的捕获组(即,在创建Matcher之前)
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)
Java文档中的示例:
Example from the Java docs:
1 ((A)(B(C)))
2 (A)
3 (B(C))
4 (C)
原则上,应该可以从(已编译的)模式中识别出这些.
In principle it should be possible to identify these from the (compiled) Pattern.
更新:从@Leniel和eslewhere来看,该功能(命名组")似乎将在2011年中期出现在Java 7中.如果我迫不及待,可以使用jregex,尽管我不太确定API是什么.
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.
推荐答案
您可以通过创建虚拟Matcher来找出组的数量,如下所示:
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());
如果您想要实际的子表达式(((A)(B(C)))
,(A)
等),则否,该信息是不可用.
If you want the actual subexpressions (((A)(B(C)))
, (A)
, etc.), then no, that information is not available.
这篇关于识别正则表达式模式中的捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!