DEV Community

Discussion on: Coding Puzzles: Week of 4/8

Collapse
 
threeheadedcerb profile image
russ

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 = match.group()
        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)