[英]how to write regex expression to find date and time
我正在讀取一個文件並在文件中查找此字符串。尋找使用正則表達式捕獲值(00:00:22)。我已經編寫了正則表達式,但沒有找到該值?
"20.10.02 00:00:22:135 INFO Running Cron : BatchJob"
Pattern p = Pattern.compile("([01][0-9]|2[0-3]):([01][0-9]|2[0-3]) INFO Running Cron", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(line);
System.out.println(m.find());
@Test
void patternTest(){
String line = "20.10.02 00:00:22:135 INFO Running Cron : BatchJob";
Pattern p = Pattern.compile(".*(\\d\\d:\\d\\d:\\d\\d):.*");
Matcher m = p.matcher(line);
assertTrue(m.matches());
System.out.println(m.group(1));
}
}
String str = "20.10.02 00:00:22:135 INFO Running Cron : BatchJob";
Pattern pattern = Pattern.compile("(?<date>\\d{2}\\.\\d{2}\\.\\d{2})\\s+(?<time>\\d{2}:\\d{2}:\\d{2}:\\d{1,3})");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println("date: " + matcher.group("date"));
System.out.println("time: " + matcher.group("time"));
} else
System.err.println("date/time not found");
\\\\d{1,2}:\\\\d{1,2}:\\\\d{1,2}
這意味着由 1 或 2 位數字分隔的三種組合:
m.find()
作為條件,使用m.group()
打印匹配的字符串。演示:
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) throws ParseException {
String line = "20.10.02 00:00:22:135 INFO Running Cron : BatchJob";
Pattern p = Pattern.compile("\\d{1,2}:\\d{1,2}:\\d{1,2}");
Matcher m = p.matcher(line);
if (m.find()) {
System.out.println(m.group());
}
}
}
輸出:
00:00:22
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.