Python用正则表达式替换第n个匹配项

时间:2018-12-16 19:19:31

标签: python regex replace substitution

我正在使用以下正则表达式:

(ADJECTIVE|NOUN|VERB)

要在下面的句子中找到这三个词:

The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.

我正在尝试运行一个循环以获取将更改ADJECTIVE,NOUN或VERB的用户输入:

new = ''
for c, item in enumerate(madlib_regexp.findall(text), 1):
    print(type(c))
    # get user input
    if item[0] == 'A':
        replace = input('Enter an ' + item.lower() + ': ')
    else:
        replace = input('Enter a ' + item.lower() + ': ')

    # replace matches with inputs
    global new
    new = madlib_regexp.sub(replace, text)

我面临的最大难题是使用枚举中的“ c”值完全替代第c个匹配项来代替我的循环。例如,“ VERB”将是我字符串中的第3个匹配项,因此我希望当前用户输入仅替换第3个匹配项。

1 个答案:

答案 0 :(得分:1)

您只需要提取要替换的值,然后使用新的re.sub调用来替换它:

import re
matches = madly_regexp.findall(text)
for c, item in enumerate(matches, 1):
    print(type(c))
    # get user input
    if item[0] == 'A':
        replace = input('Enter an ' + item.lower() + ': ')
    else:
        replace = input('Enter a ' + item.lower() + ': ')

    # replace matches with inputs
    text = re.sub(item, replace, text)
相关问题