从python列表中获取字符串之间的子字符串

2024-04-19 00:29:00 发布

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

如何从下面的列表中获取字符串&quotautoRefresh之间的内容,我只需要第一个匹配项(可能有多个匹配项)。你知道吗

['something', 'something', ' something top.window.location.href = "/commander/link/jobDetails/jobs/a2537f238-8622-11ee-a1a0-f0921c14c828?autoRefresh=0&s=Jobs";">','something']

尝试

link = re.search('"(.*?)autoRefresh', big_list)
print link.group(1)

得到TypeError: expected string or buffer


Tags: 字符串内容列表topjobslinklocationwindow
2条回答

您可以使用以下选项:

re.search(r'(?<=&quot).*?(?=autoRefresh)', ''.join(YourList))

您需要遍历列表,检查每个字符串:

big_list = ['something', 'something', ' something top.window.location.href = &quot;/commander/link/jobDetails/jobs/a2537f238-8622-11ee-a1a0-f0921c14c828?autoRefresh=0&amp;s=Jobs&quot;;">','something']

def get_all_subs(lst, pat, grp=0):
    patt = re.compile(pat)
    for s in lst:
        m = patt.search(s, grp)
        if m:
            yield m.group(grp)

print(list(get_all_subs(big_list, '&quot;(.*?)autoRefresh', 1)))

或者调用列表中的str.join,并使用findall

print(re.findall('&quot;(.*?)autoRefresh', "".join(big_list)))

相关问题 更多 >