难以理解如何将 Perl 匹配正确转换为 Python

Having difficulty understanding how to properly convert Perl match to Python

我有一个 Perl 示例,当我在 Python 中尝试相同的任务时,它看起来异常混乱且效率低下。能更好地掌握 Python 工作原理的人可以评论如何简化 python 片段,使其在简单性和编码方面更类似于 Perl 示例吗?这两个片段(Perl 和 Python)产生相同的结果。重点是测试然后提取括号内的正则表达式。 Python 案例似乎需要对正则表达式进行两次处理。


#Perl Example:
   elsif ($teststring =~ m/^([0-9\.]+)[Xx]$/)
   {
      $ExtractedVa = ;
   }
#Python Example of how to implement the perl functionality above:
    elif (re.search(r"^([0-9\.]+)[Xx]$",teststring)):  
        parts=re.search(r"^([0-9\.]+)[Xx]$",teststring)
        ExtractedVa=float(parts.group(1)) # Convert from string to numeric

在变量中记住搜索的结果:

match = re.search(r"^([0-9\.]+)[Xx]$",teststring)
if match:
    ExtractedVa=float(match.group(1)) # Convert from string to numeric

如果您使用的是 Python 3.8 或更高版本,

elif parts := re.search(....., teststring):

如果你没有达到3.8,那你就做两句:

else:
    parts = re.search(....., teststring)
    if parts:

但是你必须进一步缩进 else.

中的所有内容

“海象”运算符 := 被添加到 Python 中就是为了这种事情。

== 已编辑。 ==

我不小心在3.8代码和<3.8代码中都使用了:=。后者应该是正常的赋值运算符 '='

发布的问题没有提供足够的问题细节。

也许像下面的代码片段这样的东西应该是一个解决方案。


#!/usr/bin/env python3.7
#
# vim: ai ts=4 sw=4

import re

str = '''
192.168.0.12 server_1 room_1
192.168.0.14 server_2 room_2
192.168.0.16X server_3 room_3
192.168.0.18x server_4 room_4
192.168.0.32 server_5 room_5
'''

m = re.findall(r"^([\d\.]+)[xX]", str, re.MULTILINE)
print(m)

for ip in m:
    print(ip)

输出

['192.168.0.16', '192.168.0.18']
192.168.0.16
192.168.0.18