在与正则表达式匹配的下一行中查找数字

时间:2015-06-05 21:35:50

标签: java regex

我试图在行中的简单\s\d\d\s中找到这种形式的数字" 30 "并将其存储在int变量中,但我没有得到匹配。我该如何解决?

简单:

buildig 05:11 05:41 06:14 06:44 07:14 07:44 08:14 30 17:14 17:44 18:14 18:44 19:14 19:44

代码:

        Scanner scannerLines = new Scanner(file)) {
    int lineNum = 0;
    while (scannerLines.hasNextLine()) {
        String line = scannerLines.nextLine();
        if (line.contains(" alle ")) {
            String nextLine = scannerLines.nextLine();
            Pattern pattern = 
                    Pattern.compile("\\s\\d\\d\\s");

            Matcher matcher = 
                    pattern.matcher(nextLine);                   
             System.out.println(matcher);

        }

    }

2 个答案:

答案 0 :(得分:2)

首先,你应该在循环外编译你的模式。然后使用Matcher.find()获取与正则表达式匹配的下一个组,稍后修剪该组的值(因为" 30"中的空格)。

Pattern pattern =  Pattern.compile("\\s\\d\\d\\s");
int lineNum = 0;

Scanner scannerLines = new Scanner(System.in);
while (scannerLines.hasNextLine()) {
    lineNum++;
    while (scannerLines.hasNextLine()) {
        String line = scannerLines.nextLine();
        Matcher matcher = pattern.matcher(line);

        while (matcher.find()){
            int value = Integer.parseInt(matcher.group().trim());
            System.out.println("Found " + value + " at line " + lineNum);
        }
    }
}

答案 1 :(得分:0)

您必须使用.item { background-color: gray; } .item + .item { margin-top: 10px; } .item a { cursor: pointer; display: inline-block; background-color: blue; color: white; padding: 9px; width: 100%; height: 100%; }

matcher.find()