Python正则表达式 - 子串匹配

时间:2015-02-02 21:38:33

标签: python regex

我有一个模式

pattern = "hello"

和一个字符串

str = "good morning! hello helloworld"

我想在pattern中搜索str,以便整个字符串作为单词出现,即它不应返回hello中的子字符串helloworld。如果str不包含hello,则它应返回False。

我正在寻找正则表达式模式。

2 个答案:

答案 0 :(得分:2)

如果您希望使用正则表达式执行此任务,则可以在要搜索的模式周围使用单词边界。

>>> import re
>>> pattern  = re.compile(r'\bhello\b', re.I)
>>> mystring = 'good morning! hello helloworld'
>>> bool(pattern.search(mystring))
True

答案 1 :(得分:2)

\b匹配单词的开头或结尾。

因此模式为pattern = re.compile(r'\bhello\b')

假设您只查找一个匹配项,re.search()返回None或类类型对象(使用.group()返回匹配的确切字符串)。

对于多个匹配,您需要re.findall()。返回匹配列表(无匹配的空列表)。

完整代码:

import re

str1 = "good morning! hello helloworld"
str2 = ".hello"

pattern = re.compile(r'\bhello\b')

try:
    match = re.search(pattern, str1).group()
    print(match)
except AttributeError:
    print('No match')