簡體   English   中英

如何在字符串中搜索單詞(完全匹配)?

[英]How to search for a word (exact match) within a string?

我正在嘗試對字符串進行搜索

>>>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模塊中的方法:

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模塊。 re模塊是您應該使用的模塊。 re岩石。

我不認為in做一個正則表達式搜索。

看一下re模塊。

目前尚不清楚您實際上要做什么,但是如果您想知道“ this”是否在“ research this”中,請執行以下操作:

"this" in "researching this"

(要么)

str1 in str3

或者,如果您嘗試僅將其作為一個整體來查找,請執行以下操作:

"this" in "researching this".split()

結果是它將把“ researching this”拆分為["researching", "this"] ,然后檢查其中的確切單詞“ this”。 因此,這是錯誤的:

"this" in "researching thistles".split()

對於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!"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM