Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式字符串替换_Python_Regex - Fatal编程技术网

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
的结果赋回字符串?