Blackninja543
Blackninja543

Reputation: 3709

Python Regex String Replace

I am looking for a way to use Regex to replace a string like this:

The quick #[brown]brown#[clear] fox jumped over the lazy dog.

with

The quick <a style="color:#3B170B">brown<a style="color:#FFFFFF"> fox jumped over the lazy dog.

However the color code is picked out of a like as such

color_list = dict(
                 brown = "#3B170B",
                 .....
                 clear = "#FFFFFF",
                 )

Upvotes: 0

Views: 369

Answers (3)

Jakub M.
Jakub M.

Reputation: 33827

A crude pseudo-python solution would look like this:

for key, value in color_list.items()
  key_matcher = dict_key_to_re_pattern( key )
  formatted_value = '<a style...{0}...>'.format( value )
  re.sub( key_matcher, formatted_value, your_input_string )


def dict_key_to_re_pattern( key ):
   return r'#[{0}]'.format( key )

Upvotes: 0

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

re.sub is what you need. It takes either a replacement string or a function as its second argument. Here we provide a function because part of generating the replacement string needs is a dictionary lookup.

re.sub(r'#\[(.+?)\]', lambda m:'<a style="color:%s">' % colors[m.group(1)], s)

Upvotes: 2

dmoreno
dmoreno

Reputation: 706

Just one line of fine python should help:

reduce(lambda txt, i:txt.replace('#[%s]'%i[0],'<a style="color=%s;">'%i[1]),colors.items(),txt)

Upvotes: 0

Related Questions