2014-11-04 80 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

相關問題