Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Replace string in Assembly code - generate regex

In this solution we generate the regex from the keys of the mapping dictionary.

Once we have this we also opened other opportunities for improvement. Now that all the replacement mapping comes from a regex we have separated the "data" from the "code". We can now decide to read in the mapping from an Excel file (for example). That way we can hand over the mapping creation to someone who does not know Python. Our code will take that file, read the mapping from the spreadsheet, create the mapping dictionary, create the regex and do the work.

import sys
import re

if len(sys.argv) != 2:
    exit(f"Usage: {sys.argv[0]} FILENAME")

filename = sys.argv[1]

with open(filename) as fh:
    code = fh.read()

mapping = {
    'R1'  : 'R2',
    'R2'  : 'R3',
    'R3'  : 'R1',
    'R12' : 'R21',
    'R21' : 'R12',
}

regex = r'\b(' + '|'.join(mapping.keys()) + r')\b'
print(regex)

code = re.sub(regex, lambda match: mapping[match.group(1)], code)

print(code)