如果 string 包含 regex 模式,python 的 re: return True

我有一个这样的正则表达式:

regexp = u'ba[r|z|d]'

如果单词包含 酒吧Baz很糟糕,则函数必须返回 True。 简而言之,我需要用于 Python 的 regexp 模拟

'any-string' in 'text'

我怎么知道? 谢谢!

289691 次浏览

Match对象始终为真,如果没有匹配,则返回 None。只需测试是否为真。

密码:

>>> st = 'bar'
>>> m = re.match(r"ba[r|z|d]",st)
>>> if m:
...     m.group(0)
...
'bar'

输出 = bar

如果你想要 search的功能

>>> st = "bar"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m is not None:
...     m.group(0)
...
'bar'

如果找不到 regexp,则

>>> st = "hello"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m:
...     m.group(0)
... else:
...   print "no match"
...
no match

正如@bukzor 所提到的,如果 st = foo bar那么 match 将不起作用。因此,使用 re.search更合适。

import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
print('matched')

你可以这样做:

如果 SRE _ match 对象与搜索字符串匹配,则使用 search 将返回该对象。

>>> import re
>>> m = re.search(u'ba[r|z|d]', 'bar')
>>> m
<_sre.SRE_Match object at 0x02027288>
>>> m.group()
'bar'
>>> n = re.search(u'ba[r|z|d]', 'bas')
>>> n.group()

如果没有,它将返回无

Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
n.group()
AttributeError: 'NoneType' object has no attribute 'group'

再印出来再演示一次:

>>> print n
None

这里有一个函数可以实现你想要的功能:

import re


def is_match(regex, text):
pattern = re.compile(regex)
return pattern.search(text) is not None

正则表达式搜索方法在成功时返回一个对象,如果在字符串中没有找到该模式,则返回 Nothing。考虑到这一点,我们返回 True,只要搜索给我们一些回报。

例子:

>>> is_match('ba[rzd]', 'foobar')
True
>>> is_match('ba[zrd]', 'foobaz')
True
>>> is_match('ba[zrd]', 'foobad')
True
>>> is_match('ba[zrd]', 'foobam')
False

目前为止最好的是

bool(re.search('ba[rzd]', 'foobarrrr'))

返回 True