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

2024-04-27 21:47:22 发布

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

在下面的场景中,我找不到正确的正则表达式:

比如说:

a = "this is a sample"

我想匹配整个单词-例如match"hi"应该返回False,因为"hi"不是一个单词,"is"应该返回True,因为左右两边都没有字母字符。


Tags: samplefalsetrueismatch字母场景hi
3条回答

尝试在regex模块中使用“word boundary”字符类,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']

来自^{}的文档。

\b matches the empty string, but only at the beginning or end of a word

...

For example r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'

试试看

re.search(r'\bis\b', your_string)

来自the docs

\b Matches the empty string, but only at the beginning or end of a word.

注意,re模块使用“word”的简单定义作为“字母数字或下划线字符序列”,其中“字母数字”取决于语言环境或unicode选项。

还要注意,如果没有原始字符串前缀,\b将被视为“backspace”,而不是regex单词边界。

我认为操作人员所期望的行为并不是通过给出的答案完全实现的。具体来说,布尔值的期望输出没有完成。给出的答案有助于说明这一概念,我认为它们是优秀的。也许我可以说明我的意思,我认为OP使用了下面的例子。

给出的字符串是

a = "this is a sample"

操作人员接着说

I want to match whole word - for example match "hi" should return False since "hi" is not a word ...

据我所知,引用是指搜索标记"hi",正如在单词"this"中找到的那样。如果有人搜索字符串a来查找单词"hi",他们应该收到False作为响应。

手术继续

... and "is" should return True since there is no alpha character on the left and on the right side.

在本例中,引用是指在单词"is"中找到的搜索标记"is"。我希望这有助于澄清为什么我们使用单词边界。另一个答案的行为是“不返回一个单词,除非该单词是自己找到的,而不是在其他单词的内部。”“单词边界”shorthand character class很好地完成了这项工作。

到目前为止,示例中只使用了"is"一词。我认为这些答案是正确的,但我认为还有更多的问题的基本含义需要解决。为了理解这个概念,应该注意其他搜索字符串的行为。换句话说,我们需要用re.match(r"\bis\b", your_string)概括@georg的(优秀的)答案,re.match(r"\bis\b", your_string)同样的r"\bis\b"概念也用在@OmPrakash的答案中,他通过展示

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

假设应该展示我所讨论的行为的方法是

find_only_whole_word(search_string, input_string)

然后应该出现以下行为。

>>> a = "this is a sample"
>>> find_only_whole_word("hi", a)
False
>>> find_only_whole_word("is", a)
True

再一次,这就是我如何理解OP的问题。根据@georg的回答,我们已经朝着这种行为迈出了一步,但这有点难以解释/实现。也就是说

>>> import re
>>> a = "this is a sample"
>>> re.search(r"\bis\b", a)
<_sre.SRE_Match object; span=(5, 7), match='is'>
>>> re.search(r"\bhi\b", a)
>>>

第二个命令没有输出。@OmPrakesh给出的有用答案显示了输出,但不是TrueFalse

下面是对预期行为的更完整的抽样。

>>> find_only_whole_word("this", a)
True
>>> find_only_whole_word("is", a)
True
>>> find_only_whole_word("a", a)
True
>>> find_only_whole_word("sample", a)
True
# Use "ample", part of the word, "sample": (s)ample
>>> find_only_whole_word("ample", a)
False
# (t)his
>>> find_only_whole_word("his", a)
False
# (sa)mpl(e)
>>> find_only_whole_word("mpl", a)
False
# Any random word
>>> find_only_whole_word("applesauce", a)
False
>>>

这可以通过以下代码实现:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#@file find_only_whole_word.py

import re

def find_only_whole_word(search_string, input_string):
  # Create a raw string with word boundaries from the user's input_string
  raw_search_string = r"\b" + search_string + r"\b"

  match_output = re.search(raw_search_string, input_string)
  ##As noted by @OmPrakesh, if you want to ignore case, uncomment
  ##the next two lines
  #match_output = re.search(raw_search_string, input_string, 
  #                         flags=re.IGNORECASE)

  no_match_was_found = ( match_output is None )
  if no_match_was_found:
    return False
  else:
    return True

##endof:  find_only_whole_word(search_string, input_string)

下面是一个简单的演示。从保存文件的目录find_only_whole_word.py运行Python解释器。

>>> from find_only_whole_word import find_only_whole_word
>>> a = "this is a sample"
>>> find_only_whole_word("hi", a)
False
>>> find_only_whole_word("is", a)
True
>>> find_only_whole_word("cucumber", a)
False
# The excellent example from @OmPrakash
>>> find_only_whole_word("is", "this isis a sample")
False
>>>

相关问题 更多 >