DEV Community


Discussion on: Coding Puzzles: Week of 4/8

threeheadedcerb profile image

And now with added re.sub with a callable, which I had no idea was a thing! These coding things are pretty nifty for leaning new tricks I must say!

import re

def highlight(cmd):
    colour_map = [
        (r'F+', 'pink'),
        (r'L+', 'red'),
        (r'R+', 'green'),
        (r'\d+', 'orange'),
        (r'()+', None),

    def replacer(match : re.Match):
        substr =
        colour = next((colour for regex, colour in colour_map if re.match(regex, substr)), None)
        return '<span style="color: {}">{}</span>'.format(colour, substr) if colour else substr

    return re.sub(r'(\D)\1*|(\d+)', replacer, cmd)