Python Regex字符串替换

时间:2012-12-04 15:21:01

标签: python regex

我正在寻找一种方法来使用Regex来替换这样的字符串:

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

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

然而,颜色代码是从这样的

中挑选出来的
color_list = dict(
                 brown = "#3B170B",
                 .....
                 clear = "#FFFFFF",
                 )

3 个答案:

答案 0 :(得分:2)

re.sub就是您所需要的。它需要替换字符串或函数作为其第二个参数。这里我们提供一个函数,因为生成替换字符串需要的部分是字典查找。

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

答案 1 :(得分:0)

粗糙的伪python解决方案如下所示:

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 )

答案 2 :(得分:0)

只有一行精美的python应该有所帮助:

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