Java 匹配器。如何获取已找到组的索引?

Java 匹配器。如何获取已找到组的索引?,java,regex,matcher,Java,Regex,Matcher,我有一个句子,我想计算其中的单词,半标点符号和尾端标点符号 命令“m.group()”将显示字符串结果。但是如何知道找到了哪一组呢? 我可以使用带有“groupnull”的方法,但听起来不太好 String input = "Some text! Some example text." int wordCount=0; int semiPunctuation=0; int endPunctuation=0; Pattern pattern = Pattern.compile( "([\\w]+

我有一个句子,我想计算其中的单词,半标点符号和尾端标点符号

命令“m.group()”将显示字符串结果。但是如何知道找到了哪一组呢? 我可以使用带有“groupnull”的方法,但听起来不太好

String input = "Some text! Some example text."
int wordCount=0;
int semiPunctuation=0;
int endPunctuation=0;

Pattern pattern = Pattern.compile( "([\\w]+) | ([,;:\\-\"\']) | ([!\\?\\.]+)" );
Matcher m = pattern.matcher(input);
while (m.find()) {

//  need more correct method
if(m.group(1)!=null) wordCount++;
if(m.group(2)!=null) semiPunctuation++;
if(m.group(3)!=null) endPunctuation++;

}
您可以使用来捕获表达式

Pattern pattern = Pattern.compile( "(?<words>\\w+)|(?<semi>[,;:\\-\"'])|(?<end>[!?.])" );
Matcher m = pattern.matcher(input);
while (m.find()) {
    if (m.group("words") != null) {
        wordCount++;
    } 
  ...
}
Pattern-Pattern=Pattern.compile((?\\w+)|(?[,;:\ \-\”)|(?[!?));
匹配器m=模式匹配器(输入);
while(m.find()){
如果(m.group(“words”)!=null){
字数++;
} 
...
}

为什么不使用三个匹配器和三个循环?您可以使用单独的模式,问题就解决了。:)因为,计算单词、半标点符号和结束标点符号只需要第一个任务。第二个任务将创建的项添加到排序的集合中。开始时“ArrayList res=new ArrayList();在循环中类似这样的内容:“res.add(m.group());“这个数组列表已经排序。这就是为什么我不能使用3个单独的循环。