我正在使用 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
是一堆推送的匹配项,然后我将它们进行比较以查看堆栈中是否没有更多项目但是否存在带有结束标记的匹配项。
最佳答案
您可以使用反向方法通过创建从 0 到 start() 返回的字符数的区域来获取行号。
例如,
class MatchTest {
public static void main(String...args) {
try {
FileInputStream fis = new FileInputStream("source.txt");
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
String data = new String(buffer);
fis.close();
Pattern pattern = Pattern.compile(args[0]);
Matcher matcher = pattern.matcher(data);
while(matcher.find()) {
out.println(matcher.group());
out.println(getLine(data, matcher.start()));
}
}
catch(Exception e) {
e.printStackTrace();
}
}
static int getLine(String data, int start) {
int line = 1;
Pattern pattern = Pattern.compile("\n");
Matcher matcher = pattern.matcher(data);
matcher.region(0, start);
while(matcher.find()) {
line++;
}
return(line);
}
此处,getLine 方法将返回行号。
关于java - 使用 matcher.start() 在 matcher.find() 中获取行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7871007/