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

问题描述 投票:0回答:5

我需要用某个任意值替换正则表达式捕获组内的值;我看过

re.sub
,但它似乎以不同的方式工作。

我有一根像这样的绳子:

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

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

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

现在我想将名为 d 的组替换为

aaa
,将名为 m 的组替换为
bbb
,将名为 Y 的组替换为
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}))'

如您所见,我仍然有相同数量的捕获组(3),并且它们的命名方式相同,但结构完全不同...我需要的是像之前一样用一些任意文本替换捕获组:

'ccc-bbb-aaa'

将名为

Y
的捕获组替换为
ccc
,将名为
m
的捕获组替换为
bbb
,将名为
d
的捕获组替换为
aaa

在这种情况下,正则表达式并不是完成这项工作的最佳工具,我愿意接受其他一些可以实现我的目标的建议。

python regex python-2.7
5个回答
9
投票

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

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

"""
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'

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
投票

扩展 Python 3.x 扩展示例解决方案(

re.sub()
具有 replacement 功能):

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]

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'})
    )    

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

或者您可以将两种模式连接(“或”)在一起


0
投票
def replace_named_group_with_dict_values(pattern:str,text:str,map:dict):
    for k,v in map.items():
        if match := re.search(pattern, text):
            text = text[:match.start(k)] + str(v) + text[match.end(k):]
    return text
values = {
    'd' : 'aaa',
    'm': 'bbb',
    'Y': 'ccc',
}
s = 'monthday=1, month=5, year=2018'
p = r'monthday=(?P<d>\d{1,2}), month=(?P<m>\d{1,2}), year=(?P<Y>20\d{2})'
print(replace_named_group_with_dict_values(p,s,values))
© www.soinside.com 2019 - 2024. All rights reserved.