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 - using alternatives

We can solve the first issue by changing the regex. Instead of using a character class, we use alternatives (vertical line, aka. pipe) and fully write down the original strings.

The rest of the code is the same and the second issue is not solved yet, we still have to make sure the keys of the dictionary and the values in the regex are the same.

However this solution makes it easier to solve the second issue as well.

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

code = re.sub(r'\b(R1|R2|R3|R12)\b', lambda match: mapping[match.group(1)], code)

print(code)