在python列表中使用regex(re.search)

时间:2015-05-21 02:49:53

标签: python regex list

我有以下代码

import re

pattern = ['A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AUA', 'A-minor Type I AUA', 'A-minor Type II AGC', 'A-minor Type II AGC']

n = len(pattern)
print pattern
pattern_str = ', '.join(pattern)
print pattern_str
for x in range(0, n):
    if re.search(r'\bType I\b', pattern_str):
        print "Hello Type I"
    elif re.search(r'\bType II\b', pattern_str):
        print "Hello Type II"
    else:
        print "An error has occured"

所需的输出应为:

Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type II
Hello Type II

但我没有得到理想的输出。我目前的输出是:

Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I

有人可以指出问题吗?我怀疑它必须与列表到str转换有关。我已设法使用以下代码解决问题:

for x in pattern:
    if re.search(r'\bType I\b', x):
        print "Hello Type I"
    elif re.search(r'\bType II\b', x):
        print "Hello Type II"
    else:
        print "An error has occured"   

但我想知道为什么我的第一个代码不起作用,我怎样才能使它工作。任何帮助表示赞赏

3 个答案:

答案 0 :(得分:2)

您将整个列表加入一个字符串,然后测试一大堆。相反,你想要的是测试列表中的每个字符串,如

for pattern_str in pattern:
    if re.search(r'\bType I\b', pattern_str):
        print "Hello Type I"
    elif re.search(r'\bType II\b', pattern_str):
        print "Hello Type II"
    else:
        print "An error has occured"

所以你要一次一个地搜索每个模式

答案 1 :(得分:1)

您想要什么:搜索列表中的每个字符串。

您的代码的作用

re.search(r'\bType I\b', pattern_str)

它在循环的每次迭代中搜索pattern_str。什么是pattern_str:

pattern_str = ', '.join(pattern)

因此,在每次迭代中,它搜索相同的字符串,这是整个列表的连接,它始终与A-minor Type I AGC中的类型I匹配。

更改以搜索x中的每个pattern可以解决问题

答案 2 :(得分:0)

每次迭代的模式都是相同的。您需要在for循环中循环遍历模式。

使用for p in pattern

这意味着p在第一次迭代时为'A-minor Type I AGC',在第二次迭代时为'A-minor Type I AGC'等。

import re

pattern = ['A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AUA', 'A-minor Type I AUA', 'A-minor Type II AGC', 'A-minor Type II AGC']

for p in pattern:
    if re.search(r'\bType I\b', p):
        print "Hello Type I"
    elif re.search(r'\bType II\b', p):
        print "Hello Type II"
    else:
        print "An error has occured"

输出:

Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type II
Hello Type II