【发布时间】:2011-12-13 20:02:24
【问题描述】:
我正在使用while(matcher.find()) 循环并从文件中检索内容。我想知道如果我知道我发现的索引位于matcher.start(),我将如何从这个循环中获取行号。
我很困惑,谁能解释一下?
String expr = "<[^<?!>]+>";
String[] response = new String[5];
Pattern p = Pattern.compile(expr);
Matcher m = p.matcher(xmlDocument);
while (m.find()) {
// System.out.println(m.group() + " located at " + m.start());
// txtMatches.append(m.group() + " located at " + m.start() + "\n");
if (itemStack.getCount() == 0 && m.group().contains("</")) {
response[0] = "Orphan closing tag" ;
response[1] = stripUnwantedChars(m.group(), true);
response[2] = String.valueOf(m.start()); //right here is where i want to return line number
return response;
}
//rest of code
itemStack 是一堆推送的匹配项,然后我将它们进行比较以查看堆栈中是否没有更多项目但有一个带有结束标记的匹配项。
【问题讨论】:
-
您是为每一行构建一个单独的匹配器,还是为文件的全部内容构建一个匹配器,或者其他什么?一些代码会很好。
-
每行没有单独的匹配器。现在一个用于整个文件。并循环使用此 regex = "]+>" 查找所有文本让我看看是否可以简化一些代码以发布