【发布时间】:2013-01-10 08:20:19
【问题描述】:
我正在尝试获取在文档中找到的每个模式的索引。到目前为止,我有:
String temp = "This is a test to see HelloWorld in a test that sees HelloWorld in a test";
Pattern pattern = Pattern.compile("HelloWorld");
Matcher matcher = pattern.matcher(temp);
int current = 0;
int start;
int end;
while (matcher.find()) {
start = matcher.start(current);
end = matcher.end(current);
System.out.println(temp.substring(start, end));
current++;
}
出于某种原因它一直只在temp 中找到HelloWorld 的第一个实例,但这会导致无限循环。老实说,我不确定你是否可以使用matcher.start(current) 和matcher.end(current) - 这只是一个疯狂的猜测,因为matcher.group(current) 以前工作过。这次我需要实际的索引,所以 matcher.group() 对我不起作用。
【问题讨论】:
标签: java regex pattern-matching