【发布时间】:2011-11-30 07:18:01
【问题描述】:
我正在尝试子串搜索
>>>str1 = 'this'
>>>str2 = 'researching this'
>>>str3 = 'researching this '
>>>"[^a-z]"+str1+"[^a-z]" in str2
False
>>>"[^a-z]"+str1+"[^a-z]" in str3
False
我想在 str3 中查找时为 True。我做错了什么?
【问题讨论】:
我正在尝试子串搜索
>>>str1 = 'this'
>>>str2 = 'researching this'
>>>str3 = 'researching this '
>>>"[^a-z]"+str1+"[^a-z]" in str2
False
>>>"[^a-z]"+str1+"[^a-z]" in str3
False
我想在 str3 中查找时为 True。我做错了什么?
【问题讨论】:
你想要 Python 的 re 模块:
>>> import re
>>> regex = re.compile(r"\sthis\s") # \s is whitespace
>>> # OR
>>> regex = re.compile(r"\Wthis\W")
>>> # \w is a word character ([a-zA-Z0-9_]), \W is anything but a word character
>>> str2 = 'researching this'
>>> str3 = 'researching this '
>>> bool(regex.search(str2))
False
>>> regex.search(str3)
<_sre.SRE_Match object at 0x10044e8b8>
>>> bool(regex.search(str3))
True
我有一种预感,您实际上是在寻找“this”这个词,而不是围绕它的非单词字符的“this”。在这种情况下,您应该使用单词边界转义序列\b。
【讨论】:
看起来您想使用正则表达式,但您使用的是普通字符串方法。你需要使用re module中的方法:
import re
>>> re.search("[^a-z]"+str1+"[^a-z]", str2)
>>> re.search("[^a-z]"+str1+"[^a-z]", str3)
<_sre.SRE_Match object at 0x0000000006C69370>
【讨论】:
re.search("[^a-z]"+'researching'+"[^a-z]", str3) 搜索“研究”,我没有得到任何对象值。我做错了什么?
\b 的部分。
对于 Python 中的正则表达式,请使用 re 模块:
>>> import re
>>> re.search("[^a-z]"+str1+"[^a-z]", str2) is not None
False
>>> re.search("[^a-z]"+str1+"[^a-z]", str3) is not None
True
【讨论】:
import re
str1 = 'this'
str2 = 'researching this'
str3 = 'researching this '
if re.search("[^a-z]"+str1+"[^a-z]", str2):
print "found!"
if re.search("[^a-z]"+str1+"[^a-z]", str3):
print "found!"
【讨论】:
我认为in 不会进行正则表达式搜索。
看看re 模块。
目前尚不清楚您实际上要做什么,但是如果您想知道“this”是否在“researching this”中,请执行以下操作:
"this" in "researching this"
(或)
str1 in str3
或者,如果您只想找到整个单词,请执行以下操作:
"this" in "researching this".split()
结果是它将“researching this”拆分为["researching", "this"],然后检查其中的确切单词“this”。所以,这是错误的:
"this" in "researching thistles".split()
【讨论】:
str1 in "researching thistles" 应该返回 False)。
使用re 模块。 re 模块是您应该使用的模块。 re岩石。
【讨论】: