簡體   English   中英

字符串完全匹配

[英]String exact match

我有一個字符串,其中多次出現“本地”一詞。 我使用find() function 來搜索這個詞,但它也返回另一個詞“本地”。 我怎樣才能完全匹配“本地”這個詞?

對於這種事情,正則表達式非常有用:

import re

print(re.findall('\\blocal\\b', "Hello, locally local test local."))
// ['local', 'local']

\\b 基本上是指單詞邊界。 可以是空格、標點符號等。

編輯評論:

print(re.sub('\\blocal\\b', '*****', "Hello, LOCAL locally local test local.", flags=re.IGNORECASE))
// Hello, ***** locally ***** test *****.

顯然,如果您不想忽略這種情況,您可以刪除 flags=re.IGNORECASE。

下面你可以使用簡單的功能。

def find_word(text, search):

   result = re.findall('\\b'+search+'\\b', text, flags=re.IGNORECASE)
   if len(result)>0:
      return True
   else:
      return False

使用:

text = "Hello, LOCAL locally local test local."
search = "local"
if find_word(text, search):
  print "i Got it..."
else:
  print ":("
line1 = "This guy is local"
line2 = "He lives locally"

if "local" in line1.split():
    print "Local in line1"
if "local" in line2.split():
    print "Local in line2"

只有 line1 會匹配。

您可以使用正則表達式將匹配項限制在單詞邊界處,如下所示:

import re
p = re.compile(r'\blocal\b')
p.search("locally") # no match
p.search("local") # match
p.findall("rty local local k") # returns ['local', 'local']

對 \\blocal\\b 進行正則表達式搜索

\\b 是一個“單詞邊界”,它可以包括行首、行尾、標點等。

您還可以不區分大小寫地搜索。

尋找“本地”? 請注意,Python 區分大小寫。

使用 Pyparsing:

import pyparsing as pp

def search_exact_word_in_string(phrase, text):

    rule = pp.ZeroOrMore(pp.Keyword(phrase))  # pp.Keyword() is case sensitive
    for t, s, e in rule.scanString(text):
      if t:
        return t
    return False

text = "Local locally locale"
search = "Local"
print(search_exact_word_in_string(search, text))

哪個產量:

['Local']

quote = "No good deed will go unrewarded"

location = quote.rfind("go")
print(location)
// use rfind()

如果您想檢查是否存在,請嘗試以另一種方式思考...您可以制作這樣的東西...

檢查一個不等於你想要的模式,如果有一個匹配,然后檢查結果是否等於你想要的。

    st1:str ='local!'
    st2:str =' locally!'
    match1 = re.search(r'local\w?',st1)
    match2 = re.search(r'local\w?',st2)
    print('yes' if match1 and match1.group()=='local' else 'no')
    print('yes' if match2 and match2.group()=='local' else 'no')

暫無
暫無

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

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