1

好的所以我有我想用作正则表达式搜索的字符串列表。例如

import re
regex_strings = ['test1','test2','test3']

#Obviously this won't work here as is!  
regex = re.compile(regex_strings)

我还有另一个字符串列表。例如

strgs = ['This is a test1','This is a test2','This is a test1','This is a test1','This is a test3']

我想遍历“strgs”列表并正则表达式对照“regex_strings”列表检查每个字符串。然后,如果有匹配,则返回整个字符串。

我一直在这里摸不着头脑,我不太确定解决这个问题的最佳方法。任何建议将不胜感激!

问候。

4

3 回答 3

1

您可以|像这样在正则表达式中使用运算符

re.compile("(" + "|".join(regex_strings) + ")")

所以,正则表达式变成了这样(test1|test2|test3)。您可以在此处查看此正则表达式的含义http://regex101.com/r/pR5pU1

样品运行:

import re
regex_strings = ['test1','test2','test3']
regex = re.compile("(" + "|".join(regex_strings) + ")")
strgs = ['This is a test1','This is a test2','This is a test1','This is a test1','This is a test3']
print [strg for strg in strgs if regex.search(strg)]

输出

['This is a test1', 'This is a test2', 'This is a test1', 'This is a test1', 'This is a test3']

编辑:如果您只想返回匹配的部分,

import re
regex_strings = ['test1','test2','test3']
regex = re.compile("(" + "|".join(regex_strings) + ")")
strgs = ['This is a test1','This is a test2','This is a test1','This is a test1','This is a test3']
result = []
for strg in strgs:
    temp = regex.search(strg)
    if temp:
        result.append(temp.group())
print result

输出

['test1', 'test2', 'test1', 'test1', 'test3']
于 2013-11-12T12:49:57.977 回答
0

如果它不是太多的数据并且你的正则表达式不必编译,这一行就可以了。

print [ s for s in strgs for reg in regex_strings if re.search(reg, s) ]

否则,也许这会有所帮助:

import re
compiled_regs = map(re.compile, regex_strings)
print [ s for s in strgs for reg in compiled_regs if reg.search(s) ]

两种情况下的输出:

['This is a test1', 'This is a test2', 'This is a test1', 'This is a test1', 'This is a test3']
于 2013-11-12T12:58:32.397 回答
0

有更好的方法可以做到这一点,其他答案是这种方法的好例子,但我想我会从一开始就去

让我们逐步考虑这个问题。现在不需要编译,所以让我们跳过它。

您想遍历 strgs 并检查每个字符串。这给我们留下了。

for string in strgs:
    check it against each string in regex_string

这显然扩展到

for string in strgs:
    for regex_string in regex_strings:
       check string against regex_string and print if matching

现在唯一的问题是,如何根据正则表达式检查字符串。通过谷歌快速浏览会得到这个页面http://docs.python.org/2/howto/regex.html,或者

re.match(regex_string, string)

包括这给

for strg in strgs:
    for regex_string in regex_strings:
       m = re.match(regex_string, strg)
       if m: #short for if m != None
           print value of m

回到正则表达式 howto 给我们 m.string 留下完整的代码

for strg in strgs:
    for regex_string in regex_strings:
       m = re.match(regex_string, strg)
       if m: #short for if m != None
           print m.string

完成这些步骤后,添加正则表达式的编译并不难,所以我把它留给你。

于 2013-11-12T12:59:41.170 回答