從我的理解,假設你有字符串"John writes about this, and John writes about that"
和模式"(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
你的意思是使用'java.util.regex.matcher'? – 2013-03-04 02:40:42
是的,除非有另一種方式,我是新來的 – 2013-03-04 02:41:57
不會導致無限循環(While(regexMatcher.group().length()!= 0)? – 2013-03-04 02:51:30