perl到python的转换

2024-04-18 15:30:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试解析flie,但它的格式如下:

file.txt
10.202.34.35 username password
10.202.34.36 username password

在perl中,我可以使用regex来完成,比如

m/^(\d{1-3}.\d{1-3}.\d{1-3}.\d{1-3})\s(\w+)\s(\w+)/ then $ip = $1; $username = $2; $password = $3

如何在python中复制它?提前谢谢。你知道吗


Tags: iptxt格式usernamepasswordperlregexfile
2条回答

为什么要在这里使用regex??你知道吗

试试split

with open('file.txt') as f:
    for x in f:
        ip, username, password = x.strip().split()
        # do your stuff with variables now

这里有一个修正的正则表达式(没有Amadan在评论中提到的bug):

import fileinput
import re

pattern = '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s(\w+)\s(\w+)'

for line in fileinput.input():
    matches = re.match(pattern, line)
    if matches:
        ip, username, password = matches.groups()
        print ip, username, password

相关问题 更多 >