gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:24:09 31 4
gpt4 key购买 nike

我试图在行中的简单 "30 " 中找到这种形式的数字 \s\d\d\s 并将其存储在 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);

}

}

最佳答案

首先,您应该在循环外编译您的模式。然后使用 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);
}
}
}

关于java - 在下一行中查找与正则表达式匹配的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30676196/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com