簡體   English   中英

檢查字符串是否包含列表python中的字符串

[英]Check a string if it contains a string that's inside a list python

String = "Alienshave just discovered a way to open cans"
Arr=["Aliens","bird","cactus","John Cena"]

if any(words in String for words in arr):
       print String

這個腳本顯示Alienshave just discovered a way to open cans

但我不希望它print String ,因為這個詞AlienshaveString是不完全一樣的字Aliens中發現的Arr

我如何做到這一點,以便比較的基礎是數組中的字符串,並不像通配符那樣行事。

使用帶有單詞邊界的正則表達式( \\b ):

匹配空字符串,但僅匹配單詞的開頭或結尾。 單詞被定義為Unicode字母數字或下划線字符的序列,因此單詞的結尾由空格或非字母數字的非下划線Unicode字符表示。 請注意,正式地, \\b被定義為\\w\\W字符之間的邊界(反之亦然),或者在\\ w和字符串的開頭/結尾之間。 這意味着r'\\bfoo\\b'匹配'foo''foo.' '(foo)''bar foo baz'但不是'foobar''foo3'


string = "Alienshave just discovered a way to open cans"
arr = ["Aliens","bird","cactus","John Cena"]

import re
pattern = r'\b({})\b'.format('|'.join(arr)) # => \b(Aliens|bird|cactus|John Cena)\b
if re.search(pattern, string):
    print(string)
# For the given `string`, above `re.search(..)` returns `None` -> no print

我使用String.split()將字符串拆分為單詞。

暫無
暫無

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

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