条件python正则表达式

问题描述 投票:-1回答:1

我正在尝试使用以下正则表达式解析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>.*))"

它可以使用以下模式解析输出。

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

但是无法正确解析以下输出。

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

是否有任何单一的正则表达式可以解析上述模式?

python regex
1个回答
0
投票

你可以为硬编码的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

© www.soinside.com 2019 - 2024. All rights reserved.