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])
Oooh, I like this. I was thinking about a dictionary but didn't think about a dictionary with the regex as a key!
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)
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Oooh, I like this. I was thinking about a dictionary but didn't think about a dictionary with the regex as a key!
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!