DEV Community

Discussion on: Coding Puzzles: Week of 4/8

Collapse
 
threeheadedcerb profile image
russ • Edited
import re

def highlight(cmd):
    colour_map = [
        (r'F+', 'pink'),
        (r'L+', 'red'),
        (r'R+', 'green'),
        (r'\d+', 'orange'),
        (r'()+', None),
    ]
    highlighted = []
    while(len(cmd)):
        for regex, colour in colour_map:
            match = re.match(regex, cmd)
            if match:
                idx_start, idx_end = match.span()
                highlighted.append((cmd[idx_start:idx_end], colour))
                cmd = cmd[idx_end:]
                break
        else:
            highlighted.append((cmd[0], None))
            cmd = cmd[1:]
    return ''.join(['<span style="color: {}">{}</span>'.format(colour, string) if colour else string for string, colour in highlighted])
Collapse
 
laurieontech profile image
Laurie

Oooh, I like this. I was thinking about a dictionary but didn't think about a dictionary with the regex as a key!

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)