2024-10-02 04:26:55 发布
网友
我正在尝试一个简单的regex代码来匹配以下内容:
line = 'blah black blacksheep blah' if re.match(r'(\bblack\b)', line): print 'found it!
我做错什么了,我自己找不到“黑”?在
您应该在此处使用re.search或{}:
re.search
>>> strs = 'blah black blacksheep blah' >>> re.search(r'\bblack\b', strs).group(0) 'black' >>> re.findall(r'\bblack\b', strs) ['black']
您想要re.search而不是{}。从docs:
7.2.5.3. 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).
7.2.5.3. 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).
re.match()
re.search()
来自the docs:
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.
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
您可能需要使用re.search或re.findall。在
re.findall
您应该在此处使用}:
re.search
或{您想要}。从docs:
re.search
而不是{来自the docs:
您可能需要使用
re.search
或re.findall
。在相关问题 更多 >
编程相关推荐