0

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",
                 )
4
  • @Eric At this point not much, I have tried using re.sub() however I cannot to my knowledge use re.group() to pull out the partiular name of the color I want. Commented Dec 4, 2012 at 15:24
  • Do you have control over your input string? That would be a good situation in which to use string formatting if so. Commented Dec 4, 2012 at 15:25
  • @RocketDonkey No I don't have control over the input string. Commented Dec 4, 2012 at 15:26
  • 1
    you miss </a> closing tag... Commented Dec 4, 2012 at 15:26

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

I am finding the re.sub function does not seem to work even when I implement something such as re.sub(r'#\[brown\]', colors['brown'], s) which should return the string to The quick brown #3B170Bfox#[clear] jumped over the lazy dog.
I renamed color_list to colors. Are you forgetting to update that name?
No in fact I used a completely different name in my code and was thrown an error to fix it, after the fix there was no change in the string.
@Blackninja543: Are you assigning the result of re.sub back to your string?
0

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)

1 Comment

Looks like Haskell-derived perfectly unreadable one-liner : ) . Although I like the idea
0

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 )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.