2013-09-28 38 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()