我有syslog喜欢:
Apr 22 11:52:44 localhost systemd: Stopped logstash.
Apr 22 11:52:07 localhost systemd: Started Getty on tty1.
Apr 22 11:52:07 localhost systemd: Started Hostname Service.
Apr 22 11:52:07 localhost systemd: Started Import network configuration from initramfs.
我希望在状态之后获得3个单词(短程序名称)。
我的解决方案
"\bsystemd:\s+\S+\s\K\S+\s\S+\s\S+"
但是,程序名称可以少于3个单词(就像我的日志中的logstash),这就是为什么我需要正则表达式匹配1或2或3个单词,具体取决于字符串的长度。
我该如何解决这个问题?
你可以用
\bsystemd:\s+\S+\s\K\S+(?:\s\S+){0,2}
\S+(?:\s\S+){0,2}
部分完成这项工作:它匹配1 +非空白字符,然后是1到1个空格的0到2次重复,然后是1 +非空白字符。
看到正则表达式图: