2016-01-24 66 views
-4

我一直在尋找一個正則表達式驗證電子郵件時,我發現這一點:爲什麼[^ @]正則表達式的行爲方式如此?

[^@][email protected][^@]+\.[^@]+ 

[^@]表達似乎不起作用像機制的文檔說它應該。

s = 'test' 

match = re.match("[^@]", s) 

print(match.group()) 

這例如打印字符串的第一個字符是t。 如果我使用正則表達式[^],我收到一個錯誤:unexpected end of regular expression。該文件說:

Special characters lose their special meaning inside sets.

[]是一套和^是一個特殊字符。

+0

確保正確的題目問題。 「[^ @]'表達式正如它所記錄的那樣正確地工作,並且還沒有其他情況發生;它是引發錯誤的'[^]'表達式。 – user2864740

回答

5

「特殊字符在集合內部失去特殊含義」的說法是真實的,因爲插入字符有兩個特殊含義;在正則表達式(它是一個錨點)的邏輯開始處,以及在字符類的開始處(or 'character set' where it forms a 'complementing set of characters')。

報告的錯誤來自[^]結構,由於字符類未關閉,所以該結構無效:^影響下一個字符。

在這種情況下,效果是]確實不是關閉字符類並且整個正則表達式「未結束」,導致正則表達式語法錯誤。


不管怎樣,錯誤報道了[^]無關與[^@]這是一個字符類,將任何字符匹配除了@。這一點,再加上不正確對焦標題,或許可以解釋一些downvotes的..

re.match("[^]", "anything") # => regex error, as explained above 
re.match("[^]]", "z")   # => match; z is not ] 
re.match("[^@]", "z")   # => match; z is not @ 
re.match("[^@]", "@")   # => no match 
0

[^]是一個特例。它的意思是「匹配不在括號內的單個字符」。有關更多詳細信息,請參閱the wiki page

0

字符^是一個特殊字符。

^Test ... matches a string that starts with Test 
    \^ ... matches the character^
[\^] ... matches the character^
[^^] ... matches a character that is not a^
[-^] ... matches a - or a^
[^-] ... matches a character that is not a - 
[\^-] ... matches a - or a^
+0

這個問題更多關於_why_這個脫字符的行爲方式,而不是表達的意思。 –

相關問題