用Python中的任意值替换命名捕获的组

时间:2017-11-20 16:38:27

标签: python regex python-2.7

我需要用一些任意值替换正则表达式的捕获组内的值;我已经查看了<some-element [ngStyle]="{'font-style': styleExp}">...</some-element> <some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element> <some-element [ngStyle]="objExp">...</some-element>,但它似乎以不同的方式工作。

我有一个像这样的字符串:

re.sub

我有一个正则表达式与捕获的组匹配,如下所示:

s = 'monthday=1, month=5, year=2018'

现在我想将名为 d 的组替换为regex = re.compile('monthday=(?P<d>\d{1,2}), month=(?P<m>\d{1,2}), year=(?P<Y>20\d{2})') ,将名为 m 的组替换为aaa,将名为 Y的组替换为bbb一样,如下例所示:

ccc

基本上我想保留所有不匹配的字符串,并用匹配的组替换一些任意值。

有没有办法达到预期的效果?

注意

这只是一个例子,我可以使用不同结构的其他输入正则表达式,但同名的捕获组......

更新

由于大多数人似乎都在关注示例数据,我添加了另一个示例,让我们说我有其他输入数据和正则表达式:

'monthday=aaa, month=bbb, year=ccc'

你可以看到我仍然拥有相同数量的捕获组(3)并且它们以相同的方式命名,但结构完全不同......我需要的是在用一些任意替换捕获组之前文字:

input = '2018-12-12'
regex = '((?P<Y>20\d{2})-(?P<m>[0-1]?\d)-(?P<d>\d{2}))'

将名为'ccc-bbb-aaa' 的捕获组替换为Y,将名为ccc的捕获组替换为m,将名为bbb的捕获组替换为{{ 1}}。

在这种情况下,正则表达式不是这项工作的最佳工具,我可以接受其他一些实现目标的提案。

4 个答案:

答案 0 :(得分:4)

这是正则表达式的完全向后使用。捕获组的目的是保存您想要保留的文本,而不是要替换的文本。

由于您以错误的方式编写了正则表达式,因此您必须手动执行大部分替换操作:

"""
Replaces the text captured by named groups.
"""
def replace_groups(pattern, string, replacements):
    pattern = re.compile(pattern)
    # create a dict of {group_index: group_name} for use later
    groupnames = {index: name for name, index in pattern.groupindex.items()}

    def repl(match):
        # we have to split the matched text into chunks we want to keep and
        # chunks we want to replace
        # captured text will be replaced. uncaptured text will be kept.
        text = match.group()
        chunks = []
        lastindex = 0
        for i in range(1, pattern.groups+1):
            groupname = groupnames.get(i)
            if groupname not in replacements:
                continue

            # keep the text between this match and the last
            chunks.append(text[lastindex:match.start(i)])
            # then instead of the captured text, insert the replacement text for this group
            chunks.append(replacements[groupname])
            lastindex = match.end(i)
        chunks.append(text[lastindex:])
        # join all the junks to obtain the final string with replacements
        return ''.join(chunks)

    # for each occurence call our custom replacement function
    return re.sub(pattern, repl, string)
>>> replace_groups(pattern, s, {'d': 'aaa', 'm': 'bbb', 'Y': 'ccc'})
'monthday=aaa, month=bbb, year=ccc'

答案 1 :(得分:2)

您可以使用正则表达式替换字符串格式:

import re
s = 'monthday=1, month=5, year=2018'
s = re.sub('(?<=\=)\d+', '{}', s).format(*['aaa', 'bbb', 'ccc'])

输出:

'monthday=aaa, month=bbb, year=ccc'

编辑:给定一个任意输入字符串和正则表达式,您可以使用如下格式:

input = '2018-12-12'
regex = '((?P<Y>20\d{2})-(?P<m>[0-1]?\d)-(?P<d>\d{2}))'
new_s = re.sub(regex, '{}', input).format(*["aaa", "bbb", "ccc"])

答案 2 :(得分:2)

扩展示例的扩展 Python 3.x 解决方案(re.sub() 替换函数) :

import re

d = {'d':'aaa', 'm':'bbb', 'Y':'ccc'}  # predefined dict of replace words
pat = re.compile('(monthday=)(?P<d>\d{1,2})|(month=)(?P<m>\d{1,2})|(year=)(?P<Y>20\d{2})')

def repl(m):
    pair = next(t for t in m.groupdict().items() if t[1])
    k = next(filter(None, m.groups()))  # preceding `key` for currently replaced sequence (i.e. 'monthday=' or 'month=' or 'year=')
    return k + d.get(pair[0], '')

s = 'Data: year=2018, monthday=1, month=5, some other text'
result = pat.sub(repl, s)

print(result)

输出:

Data: year=ccc, monthday=aaa, month=bbb, some other text

对于 Python 2.7 : 将行k = next(filter(None, m.groups()))更改为:

k = filter(None, m.groups())[0]

答案 3 :(得分:0)

我建议你使用循环

import re
regex = re.compile('monthday=(?P<d>\d{1,2}), month=(?P<m>\d{1,2}), year=(?P<Y>20\d{2})')
s = 'monthday=1, month=1, year=2017   \n'
s+= 'monthday=2, month=2, year=2019'


regex_as_str =  'monthday={d}, month={m}, year={Y}'
matches = [match.groupdict() for match in regex.finditer(s)]
for match in matches:
    s = s.replace(
        regex_as_str.format(**match),
        regex_as_str.format(**{'d': 'aaa', 'm': 'bbb', 'Y': 'ccc'})
    )    

您可以使用不同的正则表达式模式多次执行此操作

或者您可以将两种模式一起加入(&#34;或&#34;)