我正在尝试为地址匹配不同的表达式:
示例:“398 W. Broadway”
我想匹配 W. 或 E.(东)或 Pl。对于地方......等等
使用这个正则表达式非常简单
(W.|West)
例如。
但是当我输入那个时,python re 模块不匹配任何内容
>>> a
'398 W. Broadway'
>>> x = re.match('(W.|West)', a)
>>> x
>>> x == None
True
>>>
最佳答案
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 offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).
关于python正则表达式匹配确切的词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19070299/