字符串完全匹配 [英] String exact match
本文介绍了字符串完全匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,其中多次出现LOCAL"这个词.我使用 find()
函数来搜索这个词,但它也返回另一个词本地".如何准确匹配本地"一词?
I have a string in which the word "LOCAL" occurs many times. I used the find()
function to search for this word but it returns another word "Locally" as well. How can I match the word "local" exactly?
推荐答案
对于这种事情,正则表达式非常有用:
For this kind of thing, regexps are very useful :
import re
print(re.findall('\\blocal\\b', "Hello, locally local test local."))
// ['local', 'local']
\b 基本上表示词边界.可以是空格、标点符号等
\b means word boundary, basically. Can be space, punctuation, etc.
编辑评论:
print(re.sub('\\blocal\\b', '*****', "Hello, LOCAL locally local test local.", flags=re.IGNORECASE))
// Hello, ***** locally ***** test *****.
如果您不想忽略大小写,显然可以删除 flags=re.IGNORECASE.
You can remove flags=re.IGNORECASE if you don't want to ignore the case, obviously.
这篇关于字符串完全匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文