CodexBloom - Programming Q&A Platform

Regex to Match Custom Log Formats - Inconsistent Timestamp Parsing in Java

๐Ÿ‘€ Views: 489 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-03
regex java log-parsing Java

I'm confused about I'm stuck on something that should probably be simple... I'm trying to extract timestamps from a custom log format in Java, but my regex doesn't seem to match consistently. The log lines look like this: ``` [2023-10-05 14:23:45] INFO: User login successful [2023-10-05 14:24:01] behavior: Invalid password attempt [2023-10-05 14:24:10] WARN: User session timeout ``` I want to capture the timestamp portion, which is in the format `YYYY-MM-DD HH:MM:SS`. My current regex pattern is: ```java String regex = "\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]"; ``` However, when I test it using the `Pattern` and `Matcher` classes in Java, for some reason, it doesn't match the timestamps in all lines. Hereโ€™s the code I've written: ```java import java.util.regex.*; public class LogParser { public static void main(String[] args) { String logs = "[2023-10-05 14:23:45] INFO: User login successful\n[2023-10-05 14:24:01] behavior: Invalid password attempt\n[2023-10-05 14:24:10] WARN: User session timeout"; String regex = "\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(logs); while (matcher.find()) { System.out.println("Matched timestamp: " + matcher.group(1)); } } } ``` When I run this code, I expect to see all the timestamps printed out, but I'm only getting: ``` Matched timestamp: 2023-10-05 14:23:45 ``` It seems like only the first match is being captured. I suspect my regex pattern might be correct, but I'm not sure what I'm doing wrong in the matching process. Iโ€™ve verified that my input string is well-formed, and I canโ€™t figure out why itโ€™s not iterating through all matches. Any suggestions on how to fix this? I'm using Java 17 and the regex package that comes with it. Thanks in advance! I'm developing on Ubuntu 22.04 with Java. Thanks for taking the time to read this! What's the correct way to implement this?