具有可选结束字符的 PCRE2 正则表达式始终匹配可选结束字符

PCRE2 regular expression with optional ending character always matches the optional ending character

我有一个从一些日志中读取用户名的 PCRE2 表达式。 在日志中,用户名可以选择放在方括号中。 我需要通过正则表达式获取用户名,当然没有括号。

示例日志:

msg_id="1100-0005" Authentication of Firewall user [someuser@somehost] from fe80::badd:cafe was rejected, password is incorrect
msg_id="5000-0001" WebUI User anotheruser@anotherhost from 10.0.0.2 log in attempt was rejected - invalid credentials.

我想出的正则表达式(第 3 组应该是用户名):

msg_id="[0-9a-fA-F]{4}-[0-9a-fA-F]{4}"\s(Authentication of)?\s?(.*\s[Uu]ser)\s\[?(\S+)\]?\s

到目前为止,第一个日志得到 someuser@somehost],第二个日志得到 anotheruser@anotherhost。 有没有一种方法可以在不使用非贪婪选项的情况下去掉结束括号?

你可以使用

msg_id="[0-9a-fA-F]{4}-[0-9a-fA-F]{4}"(?:\s+Authentication of)?\s+(.*?\s[Uu]ser)\s\[?([^\[\]\s]+)

regex demo详情:

  • msg_id=" - 文字字符串
  • [0-9a-fA-F]{4} - 四个十六进制字符
  • - - 一个连字符
  • [0-9a-fA-F]{4} - 四个十六进制字符
  • " - 一个 " 字符
  • (?:\s+Authentication of)? - 一个或多个空格的可选序列,然后是 Authentication of string
  • \s+ - 一个或多个空格
  • (.*?\s[Uu]ser) - 第 1 组:除换行符外的零个或多个字符尽可能少,然后是空格和 Useruser
  • \s - 一个空格
  • \[? - 一个可选的 [ 字符
  • ([^\[\]\s]+) - 第 2 组:除 ][ 和空格之外的一个或多个字符。