You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

正则表达式匹配疑问:timestamp + loglevel info匹配失效求助

Fixing Regex Matching for Timestamp + Log Level When Multiple Spaces/Tabs Are Present

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 \s matches 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:27:05