如何使用正则表达式处理单词

2024-10-02 04:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试一个简单的regex代码来匹配以下内容:

line = 'blah black blacksheep blah' 
if re.match(r'(\bblack\b)', line):
    print 'found it!

我做错什么了,我自己找不到“黑”?在


Tags: 代码reifmatchlineitregexblack
3条回答

您应该在此处使用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).

来自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.searchre.findall。在

相关问题 更多 >

    热门问题