我试图将所有可能的匹配项放入数组列表返回值中,但在 regexMatcher 上调用 group 时,它仅返回最后的结果。
如何将所有匹配项放入字符串或数组或任何其他类型的变量中?
while ( regexMatcher.find() ){
if (regexMatcher.group().length() != 0){
returnvalue.add(regexMatcher.group());
Writer.println(returnvalue.add);
}
最佳答案
根据我的理解,假设您有字符串 "John writes about this, and John writes about that"
和模式 "(John)([^,]*)"
,您希望将字符串中模式的每个匹配项作为 ArrayList 返回值
的元素返回。
在本例中,将有 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
关于java - 如何将 arraylist = 设置为正则表达式的每个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15193675/