我正在破解一个转换文件类型的包,允许用户指定转换(一个python函数)和一个正则表达式,用于如何更改文件名。
在一种情况下,我有一系列正则表达式和一个输出字符串,我想用所有正则表达式组的并集展开:
import re
re_strings = ['(.*).txt', '(.*).ogg', 'another(?P<name>.*)']
regexes = map(re.compile, re_strings]
input_files = ['cats.txt', 'music.ogg', 'anotherpilgrim.xls']
matches = [regexes[i].match(input_files[i]) for i in range(len(regexes))]
outputstr = 'Text file about: 1, audio file about: 2, and another file on g<name>.'
# should be 'Text file about: cats, audio file about: music, and another file on pilgrim.xls'
我想让outputstr
用正则表达式的并集展开(也许连接对2
引用更有意义?)。我可以连接两个re,用一些没用的字符分隔它们:
final_re = re.compile('n'.join(re_strings))
final_files = 'n'.join(input_files)
match = final_re.search(final_files)
但是这强制re匹配整个文件,而不仅仅是文件名的一部分。我可以在文件之间放一个全能组一个la (.*?)
,但这肯定会弄乱组引用,它可能会弄乱原始模式(我无法控制)。我想我也可以在任何地方强制命名组,然后联合所有的正则表达式。groupdict()s…
Python不允许部分展开,所以所有的组引用都必须是有效的,所以没有机会对groupdict进行一系列的展开,比如:
for m in matches:
outputstr = m.expand(outputstr)
谢谢你的建议!
只是为了记录,这里是如何组合几个正则表达式结果的结果,并在它们之间进行替换。
给定多个查询字符串和多个正则表达式匹配:
import re
query_str = ["abcdyyy", "hijkzzz"]
re_pattern = [r"(a)(b)(?P<first_name>c)(d)",
r"(h)(i)(?P<second_name>j)(k)"]
# match each separately
matches= [re.search(p,q) for p,q in
zip(re_pattern, query_str)]
我们想做一个替换字符串,结合所有的搜索结果:
replacement = r"[4_g<first_name>_2_1:5:6:8:g<second_name>]"
要做到这一点,我们需要:
- 合并搜索结果
- 用一个代理代替合并的结果(match_substitute)
- 有一个代理对象来处理命名组,例如:"first_name"(pattern_substitute)
这是由以下代码处理的。结果在"result":
import sre_parse
#
# dummy object to provide group() function and "string" member variable
#
class match_substitute:
def __init__(self, matches):
self.data = []
for m in matches:
self.data.extend(m.groups())
self.string = ""
# regular expression groups count from 1 not from zero!
def group(self, ii):
return self.data[ii - 1]
#
# dummy object to provide groupindex dictionary for named groups
#
class pattern_substitute:
def __init__(self, matches, re_pattern):
#
# Named group support
# Increment indices so they are point to the correct position
# in the merged list of matching groups
#
self.groupindex = dict()
offset = 0
for p, m in zip(re_pattern, matches):
for k,v in sre_parse.parse(p).pattern.groupdict.iteritems():
self.groupindex[k] = v + offset
offset += len(m.groups())
match = match_substitute(matches)
pattern = pattern_substitute(matches, re_pattern)
#
# parse and substitute
#
template = sre_parse.parse_template(replacement, pattern)
result = sre_parse.expand_template(template, match)