CodexBloom - Programming Q&A Platform

Regex Not Capturing Optional Leading Characters in Custom Log Format - Need Suggestions

๐Ÿ‘€ Views: 88 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-08
regex javascript logging JavaScript

I'm converting an old project and I need help solving I'm migrating some code and I'm trying to debug Hey everyone, I'm running into an issue that's driving me crazy..... Iโ€™m working with a custom log format that sometimes includes an optional timestamp followed by a log level (like INFO or behavior), and I need to extract certain fields. The log entries look like this: ``` [2023-10-01 12:00:00] INFO User logged in [behavior] User failed to log in [2023-10-01 12:01:00] WARN User password expired ``` Iโ€™ve written the following regex pattern to capture the timestamp, log level, and the message: ```regex ^(\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})?\]\s*(INFO|behavior|WARN)?\s*(.*)$ ``` However, it seems to be failing on entries where the timestamp is absent. Specifically, Iโ€™m working with this behavior when testing: ``` Uncaught SyntaxError: Invalid regular expression: /^(\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})?\]\s*(INFO|behavior|WARN)?\s*(.*)$/: ``` Iโ€™ve tried adjusting the pattern by adding `?` to make the timestamp and log level optional, but it only partially works. When I test against the log without a timestamp, I get `null` results for the captured groups. Hereโ€™s how Iโ€™m currently testing it in JavaScript: ```javascript const regex = /^(\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})?\]\s*(INFO|behavior|WARN)?\s*(.*)$/; const logs = [ '[2023-10-01 12:00:00] INFO User logged in', '[behavior] User failed to log in', '[2023-10-01 12:01:00] WARN User password expired' ]; logs.forEach(log => { const match = regex.exec(log); console.log(match); }); ``` Iโ€™d appreciate any insights on how I can modify the regex pattern to successfully capture all fields regardless of whether the timestamp is present or not. Any best practices or suggestions for this scenario would be really helpful! This issue appeared after updating to Javascript 3.11. How would you solve this? Is there a simpler solution I'm overlooking? Any suggestions would be helpful.