问题描述
我无法为以下场景找到正确的正则表达式:
I'm having trouble finding the correct regular expression for the scenario below:
让我们说:
a = "this is a sample"
我想匹配整个单词 - 例如匹配 "hi"
应该返回 False 因为 "hi"
不是一个单词并且 "is"
应该返回 True,因为左侧和右侧没有字母字符.
I want to match whole word - for example match "hi"
should return False since "hi"
is not a word and "is"
should return True since there is no alpha character on the left and on the right side.
推荐答案
尝试
re.search(r'\bis\b', your_string)
来自文档:
\b 匹配空字符串,但只在单词的开头或结尾.
请注意,re
模块使用单词"的天真定义作为字母数字或下划线字符的序列",其中字母数字"取决于语言环境或 unicode 选项.
Note that the re
module uses a naive definition of "word" as a "sequence of alphanumeric or underscore characters", where "alphanumeric" depends on locale or unicode options.
另请注意,如果没有原始字符串前缀,\b
被视为退格"而不是正则表达式单词边界.
Also note that without the raw string prefix, \b
is seen as "backspace" instead of regex word boundary.
这篇关于Python正则表达式匹配整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!