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']
>>> 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给出的有用答案显示了输出,但不是True或False。
下面是对预期行为的更完整的抽样。
>>> 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)
>>> 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
>>>
尝试在regex模块中使用“word boundary”字符类,
re
:来自^{} 的文档。
试试看
来自the docs:
注意,
re
模块使用“word”的简单定义作为“字母数字或下划线字符序列”,其中“字母数字”取决于语言环境或unicode选项。还要注意,如果没有原始字符串前缀,
\b
将被视为“backspace”,而不是regex单词边界。我认为操作人员所期望的行为并不是通过给出的答案完全实现的。具体来说,布尔值的期望输出没有完成。给出的答案有助于说明这一概念,我认为它们是优秀的。也许我可以说明我的意思,我认为OP使用了下面的例子。
给出的字符串是
操作人员接着说
据我所知,引用是指搜索标记
"hi"
,正如在单词"this"
中找到的那样。如果有人搜索字符串a
来查找单词"hi"
,他们应该收到False
作为响应。手术继续
在本例中,引用是指在单词
"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的答案中,他通过展示假设应该展示我所讨论的行为的方法是
然后应该出现以下行为。
再一次,这就是我如何理解OP的问题。根据@georg的回答,我们已经朝着这种行为迈出了一步,但这有点难以解释/实现。也就是说
第二个命令没有输出。@OmPrakesh给出的有用答案显示了输出,但不是
True
或False
。下面是对预期行为的更完整的抽样。
这可以通过以下代码实现:
下面是一个简单的演示。从保存文件的目录
find_only_whole_word.py
运行Python解释器。相关问题 更多 >
编程相关推荐