如何在python中的数组元素中查找特定字符串

时间:2016-05-02 13:04:52

标签: python regex string list

我在python中有一个字符串列表,如果列表中的元素包含单词“parthipan”,我应该打印一条消息。但是下面的脚本无效

import re
a = ["paul Parthipan","paul","sdds","sdsdd"]
last_name = "Parthipan"
my_regex = r"(?mis){0}".format(re.escape(last_name))
if my_regex in a:
    print "matched"

列表的第一个元素包含单词“parthipan”,因此它应该打印消息。

3 个答案:

答案 0 :(得分:2)

如果您想使用正则表达式执行此操作,则无法使用in运算符。请改用re.search()。但它适用于字符串,而不是整个列表。

for elt in a:
    if re.search(my_regexp, elt):
        print "Matched"
        break # stop looking

或者更具功能性的风格:

if any(re.search(my_regexp, elt) for elt in a)):
    print "Matched"

答案 1 :(得分:2)

您不需要正则表达式,只需使用any

>>> a = ["paul Parthipan","paul","sdds","sdsdd"]
>>> last_name = "Parthipan".lower()
>>> if any(last_name in name.lower() for name in a):
...     print("Matched")
... 
Matched

答案 2 :(得分:1)

为什么不:

a = ["paul Parthipan","paul","sdds","sdsdd"]
last_name = "Parthipan"
if any(last_name in ai for ai in a):
    print "matched"

这部分也是如此:

...
import re
my_regex = r"(?mis){0}".format(re.escape(last_name))
...

编辑:

我太盲目了,不知道该做什么你需要正则表达式。如果你能提供一些真正的输入和输出,那将是最好的。这个小例子也可以用这种方式完成:

a = ["paul Parthipan","paul","sdds","sdsdd",'Mala_Koala','Czarna,Pala']
last_name = "Parthipan"
names=[]
breakers=[' ','_',',']
for ai in a:
    for b in breakers:
        if b in ai:
            names.append(ai.split(b))
full_names=[ai for ai in names if len(ai)==2]
last_names=[ai[1] for ai in full_names]

if any(last_name in ai for ai in last_names):
    print "matched"

但如果真的需要正则表达式部分,我无法想象如何找到'(?mis)Parthipan'在Parthipan'。最简单的方向是反方向的Parthipan'在'(?mis)Parthipan'。就像这里......

import re
a = ["paul Parthipan","paul","sdds","sdsdd",'Mala_Koala','Czarna,Pala']
last_name = "Parthipan"
names=[]
breakers=[' ','_',',']
for ai in a:
    for b in breakers:
        if b in ai:
            names.append(ai.split(b))
full_names=[ai for ai in names if len(ai)==2]
last_names=[r"(?mis){0}".format(re.escape(ai[1])) for ai in full_names]
print last_names
if any(last_name in ai for ai in last_names):
    print "matched"

编辑:

是的,有正则表达式你几乎没有可能......

import re
a = ["paul Parthipan","paul","sdds","sdsdd",'jony-Parthipan','koala_Parthipan','Parthipan']
lastName = "Parthipan"
myRegex = r"(?mis){0}".format(re.escape(lastName))

strA=';'.join(a)
se = re.search(myRegex, strA)
ma = re.match(myRegex, strA)
fa = re.findall(myRegex, strA)
fi=[i.group() for i in re.finditer(myRegex, strA, flags=0)]
se = '' if se is None else se.group()
ma = '' if ma is None else ma.group()

print se, 'match' if any(se) else 'no match'
print ma, 'match' if any(ma) else 'no match'
print fa, 'match' if any(fa) else 'no match'
print fi, 'match' if any(fi) else 'no match'

输出,只有第一个似乎没问题,所以只有re.search提供了正确的解决方案:

Parthipan match
 no match
['Parthipan', 'Parthipan', 'Parthipan', 'Parthipan'] match
['Parthipan', 'Parthipan', 'Parthipan', 'Parthipan'] match