2013-09-28 131 views
1

我試圖對地址匹配不同的表情:蟒蛇正則表達式匹配確切的詞

例:「398 W.百老匯」

我想匹配W.或E(東)或PL。對於地方...等

使用它的regex

(W.|West)例如是非常簡單的。

然而蟒蛇重模塊不匹配任何時候我輸入的是

>>> a 
'398 W. Broadway' 
>>> x = re.match('(W.|West)', a) 
>>> x 
>>> x == None 
True 
>>> 
+0

'.'在正則表達式中有特殊含義。 –

+1

Off topic,但'x == None'不會在所有情況下給出你期望的結果,因爲'False == None'是'True','0 == None','[] == None',以及''== == None'。要檢查是否是'None'而不是'False',使用'x是None'。 – SethMMorton

+0

謝謝你。是的,我從不在代碼中執行'== None',這只是shell。 –

回答

8

re.match在輸入字符串的開頭匹配。

要匹配任何地方,請改爲使用re.search

>>> import re 
>>> re.match('a', 'abc') 
<_sre.SRE_Match object at 0x0000000001E18578> 
>>> re.match('a', 'bac') 
>>> re.search('a', 'bac') 
<_sre.SRE_Match object at 0x0000000002654370> 

search() vs. match()

python提供基於正則表達式 兩種不同的基本操作:僅在 字符串開頭的匹配re.match()檢查,同時re.search ()檢查 字符串中任何地方的匹配(這是默認情況下Perl所做的)。

+0

如果我想替換它,該怎麼辦?我嘗試使用sub()但它沒有工作 –

+0

@Saher,你是怎麼使用'sub'的?你應該使用're.sub(old_pattern,replacement_string_or_function,target_string)'。請參閱['re.sub'文檔](http://docs.python.org/2/library/re.html#re.sub)。 – falsetru

+0

沒關係。需要轉義'\ .'。 –

3

.match()限制搜索從字符串的第一個字符開始。改爲使用.search()。還要注意.匹配任何字符(除換行符外)。如果要匹配文字時間段,請將其轉義(\.而不是簡單的.)。

-1
withWithout = raw_input("Enter with or without: \n") 
if re.match('with|without', withWithout): 
    print "You enterd :", withWithout, "So I will DO!", withWithout 
elif not re.match('with|without', withWithout): 
    print " Error! you can only enter with or without ! "  
sys.exit()