繁体   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