在我有一個正則表達式是這樣的:如果字包含酒吧,巴茲或壞python的回覆:如果正則表達式中包含返回True串
regexp = u'ba[r|z|d]'
功能必須返回true。 總之,我需要對正則表達式的模擬Python的
'any-string' in 'text'
我怎樣才能實現呢?謝謝!
在我有一個正則表達式是這樣的:如果字包含酒吧,巴茲或壞python的回覆:如果正則表達式中包含返回True串
regexp = u'ba[r|z|d]'
功能必須返回true。 總之,我需要對正則表達式的模擬Python的
'any-string' in 'text'
我怎樣才能實現呢?謝謝!
import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
print 'matched'
我正在研究類似的情況,我想搜索一個確切的字符串('xyz'),並且想知道哪一個是更有效的方法來做到這一點,我應該在給定文本中使用python的'xyz'還是使用' re.compile(r'xyz')。search(given_text)'? – bawejakunal
'[]'括號中包含一個字符類,所以你的re也匹配:>>> word ='ba |'; regexp.search(word) <_sre.SRE_Match object at 0x101030b28>。您可以刪除所有管道符號。 – radtek
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
比賽不起作用。所以,它更適合使用re.search
。
你可以做這樣的事情:
使用搜索將返回一個SRE_match對象,如果您的搜索字符串匹配。
>>> 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, text)
return pattern.search(text) is not None
正則表達式搜索方法返回如果在字符串中找不到模式,則返回None。考慮到這一點,只要搜索給我們一些東西,我們就會返回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
只需使用''布爾(re.search( 'BA [RZD]',「sometext 「))''。 –