Python正则表达式字符串替换
我正在寻找一种使用正则表达式替换如下字符串的方法:Python正则表达式字符串替换,python,regex,Python,Regex,我正在寻找一种使用正则表达式替换如下字符串的方法: The quick #[brown]brown#[clear] fox jumped over the lazy dog. 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_m
The quick #[brown]brown#[clear] fox jumped over the lazy dog.
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 )
与
粗略的伪python解决方案如下所示:
The quick #[brown]brown#[clear] fox jumped over the lazy dog.
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 )
对于键,颜色列表中的值。项()
密钥匹配器=dict密钥到密钥模式(密钥)
格式化的_值=“”。格式化(值)
re.sub(键匹配器、格式化值、输入字符串)
def dict_key_至_re_模式(key):
返回r'#[{0}]'。格式(键)
只要一行精细的python就可以帮助您:
reduce(lambda txt, i:txt.replace('#[%s]'%i[0],'<a style="color=%s;">'%i[1]),colors.items(),txt)
reduce(lambda-txt,i:txt.replace('#[%s]'%i[0],'%i[1]),colors.items(),txt)
正是您所需要的。它将替换字符串或函数作为第二个参数。这里我们提供了一个函数,因为生成替换字符串所需的一部分是字典查找
re.sub(r'#\[(.+?)\]', lambda m:'<a style="color:%s">' % colors[m.group(1)], s)
re.sub(r'\[(.+?)\]',lambda m:''%colors[m.group(1)],s)
@Eric在这一点上,我尝试了使用re.sub()
,但据我所知,我无法使用re.group()
来提取我想要的颜色的部分名称。您可以控制输入字符串吗?如果是这样的话,使用字符串格式将是一个很好的情况。@RocketDonkey不,我无法控制输入字符串。您错过了
结束标记…看起来像Haskell派生的完全不可读的一行:)。虽然我喜欢这个想法,但我发现re.sub
函数似乎不起作用,即使我实现了re.sub(r'\[brown\]',colors['brown'],s)
,它应该将字符串返回到快速棕色3B170Bfox.[clear]跳过懒狗。
我把color\u列表
重命名为colors
。您是否忘记更新该名称?不,事实上,我在代码中使用了一个完全不同的名称,并被抛出一个错误进行修复,修复后字符串中没有任何更改。@Blackninja543:您是否将re.sub
的结果赋回字符串?