Python正则表达式匹配整个单词

use*_*049 33 python regex

我无法为下面的场景找到正确的正则表达式:

让我们说:

a = "this is a sample"
Run Code Online (Sandbox Code Playgroud)

我希望匹配整个单词 - 例如,匹配"hi"应该返回False,因为"hi"它不是一个单词,并且"is"应该返回True,因为左侧和右侧没有字母字符.

geo*_*org 42

尝试

re.search(r'\bis\b', your_string)
Run Code Online (Sandbox Code Playgroud)

来自文档:

\ b匹配空字符串,但仅匹配单词的开头或结尾.

请注意,该re模块使用"word"的简单定义作为"字母数字或下划线字符序列",其中"字母数字"取决于区域设置或unicode选项.

另请注意,如果没有原始字符串前缀,\b则会将其视为"退格"而不是正则表达式字边界.

  • 此语句中需要什么 **r** - re.search(**r**'\bis\b', your_string) ? (3认同)
  • 谢谢,我添加了flags = re.IGNORECASE (2认同)

Om *_*ash 6

尝试在正则表达式模块中使用“词边界”字符类,re

x="this is a sample"
y="this isis a sample."
regex=re.compile(r"\bis\b")  # For ignore case: re.compile(r"\bis\b", re.IGNORECASE)

regex.findall(y)
[]

regex.findall(x)
['is']
Run Code Online (Sandbox Code Playgroud)

re.search().

\b 匹配空字符串,但只在单词的开头或结尾

...

例如r'\bfoo\b'匹配'foo', 'foo.', '(foo)','bar foo baz'但不匹配'foobar''foo3'