Regex to validate SMTP Responses

佐手、 提交于 2019-12-08 17:01:23

I presume you're building a string with all the response codes you receive, stripping out the rest of the message?

This is probably not the answer you want, but I can't help but get the feeling that regex is just not the right tool here. Regular expressions are good at parsing text into tokens or extracting interesting sub-strings out of a larger string. But you already have tokens (SMTP response codes) and you're trying to ensure that they arrive in the expected order. I'd just add the response codes to a queue and after every addition check whether the start of the queue matches one of the expected pattern for the state that you're in. If it does, remove that part from the queue and go to the next state. There are only a few states, so I'd just write code specific to those, rather than try to abstract it into some kind of a state machine.

If you do go the Regex way you might want to keep space in the string as separators - it would not only make it easier to match codes, but easier to read the program as well.

Edit: Thanks for posting the code. It's pretty much what I assumed. You're basically trying to create an abstract solution to this problem, so you have the ability to send an a given array of commands and expect back a given pattern of responses. You really don't need to make it abstract - the added complexity is huge and unlikely to pay off in re-use. Just write the code that says: send X, if you receive Y continue, otherwise QUIT. It will be so much easier and more readable.

It's amazing how regular expressions become so much easier after a good night of sleep, here it is:

(?>220(?>250(?>(?>334){1,2}(?>235)?)?(?>(?>250){1,}(?>354(?>250(?>221)?)?)?)?)?)?

Which can be simplified to this:

^220(?>250(?>(?>334){1,2}(?>235)?)?(?>(?>250){1,}(?>354(?>250)?)?)?)?$

Since the first response code (220) is not optional and we will always send the last QUIT command.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!