[Python] Search and replace one by one in python

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    I try to find patterns in a Markdown expression. This is my code:

    import re

    redmineToGitlabIdMap = dict()
    redmineToGitlabIdMap[150767] = { 'iid': 1 }
    redmineToGitlabIdMap[150768] = { 'iid': 2 }
    redmineToGitlabIdMap[150769] = { 'iid': 3 }

    description = '*(from redmine: issue id 150767, created on 2024-02-27 by **me**)*\n\n* Relations:\n * copied_to #150767\n * relates #150768\n * relates #150769'
    pattern = r'(\s*\* (?:relates|parent|child|copied_to)) #(\d+)'

    for _, redmineId in re.findall(pattern, description):
    targetGitlabId = redmineToGitlabIdMap[int(redmineId)]['iid']
    description = re.sub(pattern, f'\\1 #{ targetGitlabId }', description, count=1)

    print(description)



    As you can see I'm iterating the matches found by the regular expression, in order to replace them one by one by their respective values from the redmineToGitlabIdMap dictionary.

    However when I execute that, it will always only replace the very first occurrence and return this

    * Relations:
    * copied_to #3
    * relates #150768
    * relates #150769


    while this should be printed instead:

    * Relations:
    * copied_to #1
    * relates #2
    * relates #3

    Continue reading...

Compartilhe esta Página