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

2024-09-30 22:12:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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”,因此它应该打印消息。你知道吗


Tags: 字符串nameimportre脚本消息元素列表
3条回答

您不需要正则表达式,只需使用^{}。你知道吗

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

如果要使用regexp执行此操作,则不能使用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"

为什么不:

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"

但如果真的需要regex部分,我无法想象如何找到'(?“Parthipan”中的“Parthipan”。最简单的方法是反向“Parthipan”in'(?(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'

输出,只有第一个看起来没问题,所以只有检索给出适当的解决方案:

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

相关问题 更多 >