Python正则表达式 - 子字符串匹配

3
我有一个模式。
pattern = "hello"

和一个字符串

str = "good morning! hello helloworld"

我希望搜索 str 中的 pattern,使得整个字符串作为一个单词存在,即不能在 helloworld 中返回子字符串hello。如果 str 不包含 hello,则应返回 False。
我正在寻找一个正则表达式模式。

我认为你会在这里找到答案:https://dev59.com/qVbTa4cB1Zd3GeqP-F4z - Jessamyn Smith
2个回答

4

\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')

2

如果您想要使用正则表达式进行搜索,可以在要搜索的模式周围使用单词边界。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接