[英]get line number within matcher.find() using matcher.start()
我正在使用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方法將返回行號。
您需要單獨創建每行開始處的索引數組,然后可以將該數組與start()
返回的索引一起使用,以找出匹配項所在的行。 對該行索引數組進行二進制搜索會很好。 您實際上也可以通過使用與行尾匹配的正則表達式來創建此行索引列表(僅匹配'\\ n'就可以了),然后在下一個字符處開始每一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.