我使用re.sub将ARB样式的名称替换为字符串中的GLSL样式的名称。现在我想另外将所有转换的匹配项存储为一组字符串。我可以在使用re.sub的“template”语法时执行此操作吗?
代码如下:

# set of replacement rules
expl_table = [
    (r'program.env\[(\d+)\]'  , r'program_env_\1'),
    (r'program.local\[(\d+)\]', r'program_local_\1'),
]
for props in expl_table:
    (re_from, re_to) = props
    # arg = re.sub(re_from, re_to, arg)       # simple and good
    def replace_func(m):
        result = ??repl_template??(m, re_to)  # where can I find it?
        declarations.append(result)           # want to save all replacements
        return result
    arg = re.sub(re_from, replace_func, arg)

我在source code中发现了类似_subx的东西,但它似乎是关闭的。
似乎我得自己去实现它,尽管听起来很愚蠢。

最佳答案

您可以在使用re.finditer()迭代字符串时更改字符串:

# set of replacement rules
expl_table = [
    (r'program.env\[(\d+)\]'  , r'program_env_dsdsds\1'),
    (r'program.local\[(\d+)\]', r'program_local_\1'),
]

declarations = []
for props in expl_table:
    (re_from, re_to) = props

    offset = 0
    for m in re.finditer(re_from, string):
        sub = m.expand(re_to)

        string = string[:m.start()+offset] + sub + string[m.end()+offset:]
        offset = max(map(len, [sub, m.group(0)])) - min(map(len, [sub, m.group(0)]))
        declarations.append(sub)

print(string)

或者,可以“升级”同一范围内的lambda函数。通常,不允许在lambda函数中使用多个语句,但是列表理解稍微绕过了这个约束:
for props in expl_table:
    (re_from, re_to) = props
    string = re.sub(re_from,
                lambda m: [
                           (result, declarations.append(result))
                           for result in [m.expand(re_to)]
                          ][0][0],
                 string)

print(string)
print(declarations)

关于python - re.sub将模板转换为函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54566131/

10-16 19:25