java - 使用 matcher.start() 在 matcher.find() 中获取行号

标签 java regex matcher

我正在使用 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/

相关文章:

java - 使用 iText 在 Java 程序中嵌入字体

Python:如何在文本中找到 n-gram 模式?

java - 与 Java Matcher 匹配的正则表达式无法按预期找到

java - SqlRowSet 无法识别列名别名吗?

JavaFX 容器可拖动

java - FileChooser.ExtensionFilter 不过滤.url 文件

c# - 按字符拆分字符串 C#

PHP-在循环中搜索数组中的字符串

java - 匹配句子java中列表/数组的任何单词

scala - 如何使用规范测试框架从 Matcher[A] 组成 Matcher[Iterable[A]]