python正则表达式匹配确切的词

标签 python regex

我正在尝试为地址匹配不同的表达式:

示例:“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/

相关文章:

sql - Orient-db 正则表达式修饰符

javascript - 标签内内容的正则表达式

python - 如何在 pyspark 管道中打印最佳模型参数

python - 为什么 class.__weakref__ 不是 None,而 instance.__weakref__ 是 None?

不使用 db.eval() 的 django 中用于 mongodb 的 Python ORM

python - python 正则表达式中的字素支持

python - python 中的有效 zip 文件

python - sqlite3.操作错误: unrecognized token: "{"

java - 映射代码以过滤掉日志文件中每一行的某些字段

Javascript 正则表达式在 ' & ' 、 ' - ' 或 ' > ' 上分割