regex - 我的正则表达式如何匹配不受欢迎的字符串?

标签 regex linux command-line grep

首先我想澄清一下我的问题的背景。我要在面试中证明自己,面试模拟现实世界,我可以咨询任何人,做任何事情,期望我能得出正确的答案。我已经解决了很多问题,但由于我对正则表达式或 Linux 命令行不是很了解,所以我被卡住了。我要解决这个任务:

Pretend you have been watching a log file with tail -f. Pipe that into a grep invocation that filters the tail input and only shows lines matching today's date in format 'YYYY-MM-DD ' at beginning of line (for any future "today"), and containing the string '[error.critical]' in any capitalization. Be careful of the details; the matching should be exactly as described here.

为此,我创建了一个名为 log 的文件,其中包含用于测试的内容:

2018-10-03 [erroR.critical]sadkhasdhaksd

2018-10-03 sadkhasdhaksd [error.critical]

2018-10-03 sadkhasdhaksd [error.noncritical]

2018-10-26 sadkhasdhaksd [error.critical]

2018-10-03 red alert [Error.critical]

2018-10-03 red alert error.critical red alert

2018-10-03 [error.critical]

我想出了这个解决方案:

tail -f log | grep -io "^$(date +"%Y-%m-%d")".*\\[error.critical\\]

然而,他们说他们可以想象出两种会错误匹配这个正则表达式的字符串。我意识到以下问题:

  • 我没有在日期之后强制保留空间
  • 我没有正确写出结果,因为在 [error.critical] 之后应该输出额外的文本
  • 我可能也对引号有误,没有把它放在字符串的末尾

同样,我对正则表达式或 Linux 命令行不是很了解。目前的做法是

tail -f log | grep -io "^$(date +"%Y-%m-%d") .*\\[error.critical\\].*"

我深思熟虑后发现的问题都已修复。但是,他们说我在这里提出的第一个正则表达式可以匹配两种不应该出现在结果中的字符串。我意识到其中一种类型(没有空格),但我不知道另一种错误匹配我的正则表达式的字符串类型是什么。你能告诉我什么类型的字符串会错误地匹配第一个正则表达式,除了那些在日期后省略空格的字符串吗?

最佳答案

你可以使用这个grep:

tail -f log | grep -i "^$(date '+%Y-%m-%d') .*\[error\.critical]"

2018-10-03 [erroR.critical]sadkhasdhaksd
2018-10-03 sadkhasdhaksd [error.critical]
2018-10-03 red alert [Error.critical]
2018-10-03 [error.critical]

  • 此正则表达式在开始时匹配今天日期之后的空格。
  • .需要转义,否则匹配任意字符。
  • 无需在 BRE 中对 [. 进行双重转义。
  • 转义 ] 是可选的
  • -o 选项用于仅提取匹配的文本,因此可以避免。

关于regex - 我的正则表达式如何匹配不受欢迎的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52629466/

相关文章:

php - 在 Debian 中将 PHP 脚本作为守护进程运行

docker - 以非 root 用户身份管理 docker 时出错

command-line - 命令行工具 - 错误 - xcrun : error: unable to find utility "xcodebuild", 不是开发人员工具或位于 PATH 中

python - 解析 HTML 表格的最快、最简单和最好的方法?

REST 过滤器/搜索参数的 Java 正则表达式模式?

javascript - 正则表达式查找包含双星号包围的数字的所有内容

javascript - 在没有 DateJS 的情况下在 jQuery 中解析日期

c - 从多个管道读取数据

c - Linux 服务器 C 代码在收到信号后停止

bash - 我怎样才能对带有前导零的数字变量进行 bash 算术运算?