我正在编写一个正则表达式来解析系统日志条目。我遇到了难以解析条目的挑战,直到我按下“ CMD”。我希望将CMD之后出现的所有内容归为()。另外,请您提供一些改进正则表达式的建议
这是我的系统日志条目:
11月21日23:17:01 ubuntu-xenial CRON [10299] :( root)CMD(cd / && run-parts --report /etc/cron.hourly)
(<?month>[A-z]{3})\s(<?date>[0-9]{2}?)\s(<?time>[0-9]+:[0-9]+:[0-9]+)\s(<?hostname>[a-z]+-[a-z]+)\s(<?daemon>[A-Z]+)(<?pid>\[[0-9]+\]):\s(<?user>\([a-z]+\))
答案 0 :(得分:0)
这是我的修订,并附有评论。通常,最好对字段将包含的内容进行较少的假设。在这里,我使用的是\S
,它是“除空格之外的任何东西”。此外,\s+
将匹配一些空格,无论是一个字符还是多个字符。
(<?month>\S+) #
\s+ # added + because single digit dates might have additional spaces
(<?date>[0-9]{1,2}) # changed {2}? to {1,2} because you might have one or two digits
\s+ #
(<?time>[0-9]+:[0-9]+:[0-9]+) #
\s+ #
(<?hostname>\S+) # anything which isn't whitespace
\s+ #
(<?daemon>\S+) # just in case your daemon has a digit or lower case in its name
(<?pid>\[[0-9]+\]) #
: #
\s+ #
\((<?user>\S+)\) # your username might have digits in it; don't capture the brackets
\s+ #
CMD #
\s+ #
\((<?command>.*)\) # capture the command, not the brackets
\s* # in case of trailing space
$ # match end of string