Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
条件python正则表达式_Python_Regex - Fatal编程技术网

条件python正则表达式

条件python正则表达式,python,regex,Python,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>.*))" 但无法正确解析以下输出 PORT S

我试图用以下正则表达式解析服务发现的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
161/tcp filtered snmp       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>.*))
(?P[\d]+)\/(?Ptcp|udp)\s+(?Popen | filtered | closed)\s+(?P[\w\s]*)\s+(?P(:?:?\s*\s+\s+\s*(?=\w)\w)(:?无响应)(?:\n |(?P.*))

您考虑过使用Python映射到nmap吗?我不认为你可以用正则表达式解决这个问题,因为没有办法描述一个模式来决定一列的结束和另一列的开始。你也可以研究可选组,例如
(?:…)
,然后看。@Jerome。。。我已经尝试过nmap python模块,这真是太棒了。但是使用我现在所做的方法进行解析的目的是解析现有的nmap输出文件。nmap python模块将需要从头开始的完整开发,这将需要使用nmap模块调用nmap脚本。@Wiktor Stribizew。。。谢谢你的回复。我确实尝试过你提供的解决方案。不走运。“无响应”后下一行的端口将获得版本的一部分。将需要一些其他的解决方法来处理在“原因”值字符串之后的格式。感谢@mrzasa的快速响应。但是这个建议对我不起作用。模式差异如下。可能有“原因”值字符串,格式为“”,后跟版本字符串。原因字符串的另一种模式是“[a-zA-Z0-9]”,后跟新行字符。所提到的第一个正则表达式在遇到\n并将下一行即端口协议字符串作为版本字符串时不匹配。以下是供参考的示例输出。端口状态服务原因版本161/tcp过滤snmp无响应179/tcp打开tcpwrapped syn ack ttl 54
(?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>.*))