简体   繁体   English

有条件的python正则表达式

[英]Conditional python regex

I am trying to parse the nmap output for service discovery with the following regex.我正在尝试使用以下正则表达式解析服务发现的 nmap 输出。

regex = "(?P<ports>[\d]+)\/(?P<protocol>tcp|udp)\s+(?P<state>open|filtered|closed)\s+(?P<service>[\w\S]*)\s+(?P<reason>\S*\s+\S+\s+\S*(?=\w)\w)(?:\n|(?P<version>.*))"

It could parse the output with the following pattern.它可以使用以下模式解析输出。

PORT    STATE    SERVICE    REASON         VERSION
80/tcp   open     http     str1 str2 str3    version string here

But is not able to correctly parse the following output.但无法正确解析以下输出。

PORT    STATE    SERVICE    REASON         VERSION
161/tcp filtered snmp       no-response

Is there any single regex which can parse both the above patterns?是否有任何一个正则表达式可以解析上述两种模式?

You can add an alternative for hardcoded no-response , would it help?您可以为硬编码的no-response添加一个替代方案,它会有所帮助吗?

(?P<ports>[\d]+)\/(?P<protocol>tcp|udp)\s+(?P<state>open|filtered|closed)\s+(?P<service>[\w\S]*)\s+(?P<reason>(:?\S*\s+\S+\s+\S*(?=\w)\w)|(:?no-response))(?:\n|(?P<version>.*))

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM