正则表达式匹配疑问:timestamp + loglevel info匹配失效求助
Got it, let's sort out why your regex isn't catching the timestamp and log level when there are multiple spaces or tabs after something like DEBUG. The most likely culprit is that your current pattern only looks for a single whitespace character instead of accounting for one or more (including tabs).
Let's break down the problem and fix it
- Root cause: If your original regex uses a single space (like
(timestamp) (DEBUG)), it will fail when there are two+ spaces or a tab—since those don't match a single space. - Simple fix: Replace single spaces with
\s+, where\smatches any whitespace character (spaces, tabs, newlines, etc.) and+means "one or more of the preceding character/group".
Example Working Regex
Let's assume your logs follow a common format like [timestamp] [log level] [message]. Here's a regex that handles multiple whitespace:
^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s+(DEBUG|INFO|WARN|ERROR)\s+(.*)$
What each part does:
^: Anchors the match to the start of the line (prevents partial matches mid-line)(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}): Captures the timestamp—adjust this part if your timestamp has milliseconds, different separators, etc.\s+: Matches one or more spaces/tabs between timestamp and log level(DEBUG|INFO|WARN|ERROR): Captures the log level—add other levels as needed\s+: Again, matches one or more spaces/tabs between log level and message(.*): Captures the rest of the log message$: Anchors the match to the end of the line
Test It Out
This regex will match all these cases:
2024-05-20 14:30:00 DEBUG This log has two spaces after DEBUG
2024-05-20 14:30:01 DEBUG This log uses a tab after DEBUG
2024-05-20 14:30:02 DEBUG This log has three spaces after DEBUG
Adjustments for Your Specific Log Format
If your timestamp looks different (e.g., 2024/05/20 14:30:00.123), just tweak the timestamp capture group to match your actual format. The key fix remains using \s+ instead of single spaces wherever whitespace might vary.
内容的提问来源于stack exchange,提问作者MUHAHA

