提取字符串

时间:2017-01-03 14:41:26

标签: python regex

在这里,我想从电子邮件ID中提取 alpitananad 。到目前为止,我已经做了很多。

import re

def extracter(text):
        reg1 = re.compile(r'(\d{3}|\(\d{3}\))?(\s|-|\.)?(\d{3})(\s|-|\.)(\d{4})')
        se1 = reg1.findall(text)
        print(se1)
        for i in range(len(se1)):
               print(''.join(se1[i]))
        reg2 = re.compile(r'([a-zA-Z0-9]+@+[a-zA-Z0-9]+\.[a-zA-Z]{2,4})')
        reg3 = re.compile(r'[a-zA-Z0-9]+@')
        se3 = reg3.findall(text)
        se2 = reg2.findall(text)
        print(se2)
        print(se3)

text1 = "123-434-2432 of may name is jsdiofhsdio fh diofh dui fjf ui834y8  fwe8fweuihwe 8f e87f y87 456-243-3434 ajsfhj alpitanand20@gamil.com"
extracter(text1)

我得到的输出是

[('123', '-', '434', '-', '2432'), ('456', '-', '243', '-', '3434')]
123-434-2432
456-243-3434
['alpitanand20@gamil.com']
['alpitanand20@']

我想要一个输出来检查前一个字符串 @ 。我应该在reg3中做出哪些改变。谢谢.. !!!

1 个答案:

答案 0 :(得分:2)

以下内容应该有效:

re.findall('(\w+)@', text1)

<强>输出:

>>> import re
>>> 
>>> text1 = "123-434-2432 of may name is jsdiofhsdio fh diofh dui fjf ui834y8  fwe8fweuihwe 8f e87f y87 456-243-3434 ajsfhj alpitanand20@gamil.com"
>>> reg3 = re.compile(r'(\w+)@')
>>> se3 = reg3.findall(text1)
>>> se3
['alpitanand20']