[英]How to use regex for words
I was trying a simple regex code to match the following: 我正在尝试一个简单的正则表达式代码来匹配以下内容:
line = 'blah black blacksheep blah'
if re.match(r'(\bblack\b)', line):
print 'found it!
What am I doing wrong, I can't find "black" by itself? 我做错了什么,我自己找不到“黑色”?
re.match(pattern, string, flags=0)
If zero or more characters at the beginning of string match the regular expression pattern , return a corresponding
MatchObject
instance. 如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的MatchObject
实例。
You probably want to use re.search
or re.findall
instead. 您可能想改用re.search
或re.findall
。
You should use re.search
or re.findall
here: 您应该在此处使用re.search
或re.findall
:
>>> strs = 'blah black blacksheep blah'
>>> re.search(r'\bblack\b', strs).group(0)
'black'
>>> re.findall(r'\bblack\b', strs)
['black']
You want re.search
instead of re.match
. 您需要re.search
而不是re.match
。 From the docs : 从文档 :
7.2.5.3. 7.2.5.3。 search() vs. match() search()与match()
Python offers two different primitive operations based on regular expressions:
re.match()
checks for a match only at the beginning of the string, whilere.search()
checks for a match anywhere in the string (this is what Perl does by default). Python提供了两种基于正则表达式的原始操作:re.match()
仅在字符串的开头检查匹配项,而re.search()
在字符串的任何位置检查匹配项(这是Perl的默认设置) )。
Use re.search()
(returns None if no match on the whole string): 使用re.search()
(如果整个字符串不匹配,则返回None):
line = 'blah black blacksheep blah'
if re.search(r'(\bblack\b)', line):
print 'found it!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.