java:在文本中搜索单词并给出其行

时间:2014-04-22 08:18:04

标签: java string line

我有一个字符串输出(一个段落)有近140行,我想搜索这一段中的一个单词并在段落中得到它的行 例如我有:

date : 08/12/2009
value : 589.236
smth : smth 
Fax : 25896217

我搜索单词值,它给了我段落中的第2行, 实际上,我使用此代码来获取行数:

String resultat = "..."
Matcher m = Pattern.compile("(\n)|(\r)|(\r\n)").matcher(resultat);
    int lines = 1;
    while (m.find())
    {
        lines ++;
    }

java中有一个预定义的方法,它给出了找到的单词行吗?

2 个答案:

答案 0 :(得分:1)

一种解决方案是通过按行结束字符分割String值来获取行,并检查每行是否出现搜索到的值并返回找到的事件上的亚麻数。可能的实现可能是:

private static int findPartInArray(String[] text, String needle) {
    int lineNumber = 0;
    for (String line : lines) {
        if (line.contains(needle)) {
            return lineNumber + 1;
        }
        lineNumber++;
    }
    return -1;
}

使用示例:

String input = "date : 08/12/2009" + "\n" + "value :  589.236" + "\n"
    + "smth : smth" + "\n" + "Fax : 25896217";
String[] lines = input.split("(\\n)|(\\r)|(\\r\\n)");
int res = findPartInArray(lines, "value");
if (res > 0)
System.out.println("not found");

答案 1 :(得分:0)

据我所知,没有。所以我的解决方案是将文本分成行并逐行扫描文本,直到找到该单词。然后返回一个行号。

public class LineNumber {
    public static void main(String[] args) {
        String text = "date : 08/12/2009" + "\n" + "value : 589.236" + "\n"
                + "smth : smth" + "\n" + "Fax : 25896217";

        System.out.println("'smth' first found at line: "
                + findFirstOccurenceLineNumber(text, "smth"));
    }

    private static int findFirstOccurenceLineNumber(String text, String needle) {
        String lines[] = text.split("\r|\n|\r\n|\n\r", -1);
        int lineNumber = 1;
        for (String line : lines) {
            if (line.contains(needle)) {
                return lineNumber;
            }
            lineNumber++;
        }
        return -1;
    }
}
相关问题