0

我试图将所有可能的匹配项放入 arraylist Returnvalue 中,尽管在 regexMatcher 上调用 group 时,它只返回最后一个结果。

我如何完成将所有匹配项放入字符串或数组或任何其他类型的变量中?

while ( regexMatcher.find() ){
if (regexMatcher.group().length() != 0){
  returnvalue.add(regexMatcher.group());
  Writer.println(returnvalue.add);
}
4

1 回答 1

2

据我了解,假设您有 String"John writes about this, and John writes about that"和 pattern "(John)([^,]*)",您希望将字符串中模式的每个匹配项作为 ArrayList 的元素返回return Value

在这种情况下,将有 2 个这样的匹配项,"John writes about this"并且"John writes about that". 如果是这样,下面的简短程序将给出确切的答案。尝试更改代码以满足您的需要。

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class testCode
{
    public static void main(String args[])
    {
        String text = "John writes about this, and John writes about that";
        String patternString1 = "(John)([^,]*)";

        Pattern pattern = Pattern.compile(patternString1);
        Matcher regexMatcher = pattern.matcher(text);

        List<String> returnValue= new ArrayList<String>();

        while(regexMatcher.find())
            if(regexMatcher.group().length() != 0)
                returnValue.add(regexMatcher.group());

        for(int i=0; i<returnValue.size(); i++)
            System.out.println(returnValue.get(i));
    }
}

输出:

John writes about this
John writes about that
于 2013-03-04T04:11:53.023 回答