如何构建用于验证 smtp 错误代码的正则表达式

how can I build a regex for validating smtp error codes

我正在尝试构建一个正则表达式来读取和识别退回电子邮件中的 smtp 错误代码,因此稍后我可以将此代码与 smtp 错误代码数据库匹配并翻译成其他友好的消息。

退回电子邮件的正文响应如下所示(仅诊断代码行相关):

- Diagnostic-Code: smtp; 550-5.1.1 The email account that you tried to reach does...
- Diagnostic-Code: smtp; 553 5.1.2 Unknown mail server. Could not find a mail server...
- Diagnostic-Code: smtp; 550 5.5.0 Requested action not taken: mailbox unavailable...
- Diagnostic-Code: smtp;550 5.5.0 Requested action not taken: mailbox unavailable...
- Diagnostic-Code: smtp; 550-5.1.1 The email account that you tried to reach does not exist...

可以是两种情况:

1. 550 5.5.0 -->  3 digit number + space + 3 digit number only if followed by a dot.
2. 550-5.1.1 --> 3 digit number + hyphen + 3 digit number only if followed by a dot.

我尝试使用这个正则表达式,但没有捕获前 3 位数字和后跟一个点的后 3 位数字

(?<!\d)(\d+\.){2}(?>\d)

根据您的示例数据,此正则表达式应该符合您的要求:

(?<=smtp;) ?(\d{3})[ -]((?:\d+\.){2}\d+)

它查找字符串 smtp; 后跟一个可选的 space,然后是 3 位数字(在第 1 组中捕获),一个 space 或连字符,然后是一串数字, ., digits, ., digits(在第 2 组中捕获)。

Demo on regex101