2014-11-04 83 views
0

我正在使用单个模式来捕获正确的电子邮件地址地址与角度大括号。 根据以下情况,正确的电子邮件地址是在提供了两个大括号或未输入任何 时。Python高级模式捕获电子邮件地址

正确的电子邮件地址格式: -


1. <[email protected]> , <[email protected]> 
2. [email protected] , [email protected] 

在正确的电子邮件地址格式: -


1. <[email protected] 
2. [email protected]> 
3. <[email protected]> 
4. <abcgmail.com> 
5 <[email protected]> 

代码捕获上述电邮地址: -

'''

捕获电子邮件地址。同时允许打开和关闭角支架其他不正确的模式。 “””

import re 
# Sub pattern "(?(id)[>])" is used to compare that if the group('id') has matched then expect the closing angular brace else not. 

pattern = r'(?P<id>[<])(\[email protected]\w+)((\.\w+)+)(?(id)[>])' 
m = re.search(pattern,email,re.I) 
if m: 
    print "Correct Email:",m.group() 
else: 
    print "Incorrect Pattern!"  

上面的代码正确地匹配的情况下,当电子邮件具有角括号和当给出不正确括号(例如:错过开/闭括号)。

但模式不匹配的情况下,电子邮件没有角括号提供。

回答

0

只需使用两个正则表达式匹配的论文两种类型的电子邮件地址(1,以匹配其既不<和preceeded也不随后>符号2.以匹配其通过< preceeded和随后的电子邮件地址的电子邮件地址>符号)。通过将这两个正则表达式与|或运算符相结合,您将得到两者匹配的电子邮件。

>>> import re 
>>> s = """<[email protected]> <[email protected]> [email protected] [email protected] <[email protected]> <[email protected] [email protected]> """ 
>>> for i in re.findall(r'<\[email protected]\w+(?:\.\w+)+>|(?<!<)\b(?:\[email protected]\w+)(?:\.\w+)+\b(?!>)', s): 
    print(i) 


<[email protected]> 
<[email protected]> 
[email protected] 
[email protected] 

通过re.search功能。

>>> s = """<[email protected]> <[email protected]> [email protected] [email protected] <[email protected]> <[email protected] [email protected]>""" 
>>> for i in s.split(): 
    m = re.search(r'<\[email protected]\w+(?:\.\w+)+>|(?<!<)\b(?:\[email protected]\w+)(?:\.\w+)+\b(?!>)', i) 
    if m: 
     print("Correct Email : " + m.group()) 
    else: 
     print ("Incorrect Pattern!") 


Correct Email : <[email protected]> 
Correct Email : <[email protected]> 
Correct Email : [email protected] 
Correct Email : [email protected] 
Incorrect Pattern! 
Incorrect Pattern! 
Incorrect Pattern! 

Explanation

+0

在这个模式 - \ B(:\ w + @ \ w +?)(:\ \ w +?)+ \ B,可以(<<?!)(>?!)你解释正则表达式的两部分: - 1.(?) – 2014-11-05 16:23:56

+0

这对我有用。但是因为我没有高级知识,所以我需要一些帮助来理解两部分1.(?!>)2.(?!>)。我需要一些基本的知识来理解模式的这些部分。 – 2014-11-05 16:58:10

+0

'(?<!<)'neagative lookbehind其中声明匹配之前会有任何字符,而不是'<'符号。 ''(?!>)'nagative lookahead,它声称匹配后面会跟着任何字符,但不是'>'符号。 – 2014-11-05 17:00:53

相关问题