python的re:如果正则表达式包含在字符串中,则返回True

gho*_*nsd 81 python regex

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

regexp = u'ba[r|z|d]'
Run Code Online (Sandbox Code Playgroud)

如果单词包含bar,bazbad,则函数必须返回True .简而言之,我需要用于Python的正则表达式模拟

'any-string' in 'text'
Run Code Online (Sandbox Code Playgroud)

我怎么才能意识到这一点?谢谢!

mat*_*ski 132

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

  • 为什么字符串前面需要“r”?即 `re.compile(r'x[\d+]')` 与 `re.compile('x[\d+]')` 有什么区别? (2认同)

Ven*_*thy 92

迄今为止最好的是

bool(re.search('ba[rzd]', 'foobarrrr'))
Run Code Online (Sandbox Code Playgroud)

返回True

  • 一方面,它返回一个“bool”。OP:“如果单词包含 bar、baz 或 bad,则必须返回 `True`。” 其他答案使用“if”的行为 - 将右侧的表达式自动转换为“bool”。例如`导入重新;rgx=re.compile(r'ba[rzd]'); rgx.search('foobar')` => `<re.Match 对象; span=(2, 5), match='bar'>`,但是 `if(rgx.search(w)): print('y')` => `y`。[我能找到的最接近自动转换的文档](http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/boolean.html)([archived](https://web. archive.org/web/20200319164133/http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/boolean.html)) (4认同)
  • 为什么这比其他解决方案更好? (2认同)
  • 为什么你更喜欢“.search”而不是“.match”? (2认同)

Ran*_*Rag 14

Match对象始终为true,None如果没有匹配则返回.只是测试真实性.

码:

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

输出= bar

如果你想要search功能

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

如果regexp没有找到

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

正如@bukzor所说,如果st = foo bar匹配将无效.所以,它更适合使用re.search.