我有一种String
形式:
1,2,3,4,5,6,7,8,...
我正在尝试查找此字符串中所有包含4位数字的所有子字符串。为此,我有正则表达式[0-9],[0-9],[0-9],[0-9]
。不幸的是,当我尝试将正则表达式与我的String进行匹配时,我从未获得所有子字符串,而仅获得了所有可能子字符串的一部分。例如,在上面的示例中,我只会得到:
1,2,3,4
5,6,7,8
虽然我希望得到:
1,2,3,4
2,3,4,5
3,4,5,6
...
我将如何查找与我的正则表达式相对应的所有匹配项?
对于信息,我正在使用Pattern
并Matcher
查找匹配项:
Pattern pattern = Pattern.compile([0-9],[0-9],[0-9],[0-9]);
Matcher matcher = pattern.matcher(myString);
List<String> matches = new ArrayList<String>();
while (matcher.find())
{
matches.add(matcher.group());
}
默认情况下,连续的调用Matcher.find()
从上一场比赛的结尾开始。
要从特定位置查找,find
请将起始位置参数传递到前一个字符的开头之后的一个字符find
。
在您的情况下,可能类似于:
while (matcher.find(matcher.start()+1))
这工作正常:
Pattern p = Pattern.compile("[0-9],[0-9],[0-9],[0-9]");
public void test(String[] args) throws Exception {
String test = "0,1,2,3,4,5,6,7,8,9";
Matcher m = p.matcher(test);
if(m.find()) {
do {
System.out.println(m.group());
} while(m.find(m.start()+1));
}
}
印刷
0、1、2、3
1,2,3,4
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句