要提取的python regex用户名:密码或电子邮件:密码输入混合分隔cs

2024-04-20 04:38:07 发布

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

我有(数千)个csv文件,其中包含(数十亿)行,例如:

在组合框.csv在

example0@domain.tld:passw0rd
ex.a.m-pl_e1@domain.tld;p@££w0r46&
0-0-0 ex.a.m-pl_e1@domain.tld p@££w0r46&
ex.a.m-pl_e1@domain.tld:00-00-00;p@££w0r46& <-- updated line
00-00-00:username:password
username:p@££w0r46&
username p@££w0r46&
and more...

我正在尝试提取一些机器学习作业的电子邮件或用户名和密码。但我似乎无法确定正确的正则表达式。在

使用re.splitre.findall或{}似乎是这里的选项,我正试图编译一个regex,它允许我简单地打印,例如:

^{pr2}$

从上面combos.csv

我已经成功地使用了以下电子邮件/密码组合:

re.compile(r'(?:.*[:|;])?(?P<email>[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)[:|;](?P<Password>.*)')

但提取用户名/密码我还没处理好。我尝试过look behind on;and:但似乎当行被分隔两次时,我当前的regex将返回第一列作为username,第二列作为password:

re.compile(r'^(?:.*[:|;])?(?P<username>[A-z0-9\.\-\_\$\#\&]+)(?!@)[:|;](?P<password>.*)')

我怎样才能做到这一点,更好的是,有没有一个解决方案,一个正则表达式可以做一切?在

欢迎任何帮助!在


Tags: andcsvre密码电子邮件domainusernamepassword
2条回答

这样的怎么样:

import re

with open('file.csv', 'r') as f:
    rows = f.readlines()

data = [re.split(r'\s|;|:', row) for row in rows]
# remove the 00-00-00 bits
clean_data = [filter(lambda x: re.match(r'(0+\-+)+', x) == None, d)[:-1]
              for d in data]

mail_regex = r'[^@]+@[^@]+\.[^@]+'

for d in clean_data:
    if re.match(mail_regex, d[0]) is not None:
        print 'Email: "{}" Password: "{}"'.format(d[0], d[1])
    else:
        print 'Username: "{}" Password: "{}"'.format(d[0], d[1])

产生:

^{pr2}$

如果您计划从每行中提取电子邮件、密码和可选用户名数据,您可以使用这些数据

import re
rx = re.compile(r'[:; ]')
rx_email = re.compile(r'\S+@\S+\.\S+$')
with open(your_file, "r") as f:
    for line in f:
        fields = rx.split(line)
        email = ''
        id = ''
        for field in fields:
            if rx_email.match(field):
                email = field
            elif field != fields[-1]:
                id = field
        password = fields[-1]
        print("Username: '{}', email: '{}', password: '{}'".format(id, email, password))

this Python demo。在

^\S+@\S+\.\S+$模式匹配类似电子邮件的字段,这些字段以1+非空白字符开头,然后有@,同样是1+非空白字符。并以1+非空白字符结尾。在

re.split一起使用的[:; ]模式与;和{}一起使用。在

相关问题 更多 >