据我了解,假设您有 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