正则代数取代的组合产物

len*_*enz 6 python regex cross-product

我试图通过可选地应用替换来生成字符串变体.

例如,一种替换方案是删除任何空白字符序列.而不是替换所有出现的事件

>>> re.sub(r'\s+', '', 'a b c')
'abc'
Run Code Online (Sandbox Code Playgroud)

- 相反,我需要为每次出现生成两个变体,因为替换是在一个变体中执行,而不是在另一个变体中执行.对于字符串'a b c' 我想要变种

['a b c', 'a bc', 'ab c', 'abc']
Run Code Online (Sandbox Code Playgroud)

即.所有二元决策的叉积(结果显然包括原始字符串).

对于这种情况,可以使用re.finditer和生成变体itertools.product:

def vary(target, pattern, subst):
    occurrences = [m.span() for m in pattern.finditer(target)]
    for path in itertools.product((True, False), repeat=len(occurrences)):
        variant = ''
        anchor = 0
        for (start, end), apply_this in zip(occurrences, path):
            if apply_this:
                variant += target[anchor:start] + subst
                anchor = end
        variant += target[anchor:]
        yield variant
Run Code Online (Sandbox Code Playgroud)

这为上面的例子产生了所需的输出:

>>> list(vary('a b c', re.compile(r'\s+'), ''))
['abc', 'ab c', 'a bc', 'a b c']
Run Code Online (Sandbox Code Playgroud)

但是,此解决方案仅适用于固定字符串替换.re.sub类组引用的高级功能不能像这样完成,如下面的示例,用于在单词内的一系列数字后面插入空格:

re.sub(r'\B(\d+)\B'), r'\1 ', 'abc123def')
Run Code Online (Sandbox Code Playgroud)

如何扩展或更改方法以接受re.sub的任何有效参数(不编写用于解释组引用的解析器)?

B98*_*B98 1

考虑制作subst一个可以访问匹配数据的可调用对象,最终让我了解了MatchObject.expand. 因此,作为近似值,subst保留一根r绳子,

def vary(target, pattern, subst):
    matches = [m for m in pattern.finditer(target)]
    occurrences = [m.span() for m in matches]
    for path in itertools.product((True, False), repeat=len(occurrences)):
        variant = ''
        anchor = 0
        for match, (start, end), apply_this in zip(matches, occurrences, path):
            if apply_this:
                variant += target[anchor:start] + match.expand(subst)
                anchor = end
        variant += target[anchor:]
        yield variant
Run Code Online (Sandbox Code Playgroud)

不过,我不确定这是否涵盖了引用主题字符串所需的所有灵活性,并绑定到相应的匹配项。我想到了分割字符串的索引幂集,但我想这离提到的解析器并不远。