[英]Check if a Python list item contains a string inside another string but with conditions
[英]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
,因为这个词Alienshave
的String
是不完全一样的字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.