0

正規表現を使用して次のような文字列を置き換える方法を探しています:

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",
                 )
4

3 に答える 3

2

re.sub必要なものです。2番目の引数として、置換文字列または関数のいずれかを取ります。ここでは、必要な置換文字列の生成の一部が辞書検索であるため、関数を提供します。

re.sub(r'#\[(.+?)\]', lambda m:'<a style="color:%s">' % colors[m.group(1)], s)
于 2012-12-04T15:35:05.147 に答える
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 )
于 2012-12-04T15:24:23.757 に答える
0

細かい python の 1 行だけが役に立ちます。

reduce(lambda txt, i:txt.replace('#[%s]'%i[0],'<a style="color=%s;">'%i[1]),colors.items(),txt)
于 2012-12-04T15:28:05.350 に答える