Python 替换捕获组中的多个字符
我需要将方括号替换为花括号,下划线替换为空格 输入:Python 替换捕获组中的多个字符,python,regex,Python,Regex,我需要将方括号替换为花括号,下划线替换为空格 输入: [something\u id='123'\u more-info='321'] 迄今为止的产出: {something\u id='123''u more-info='321'} 所需输出: {something id='123'more info='321'} 我可以替换括号,但我不知道从哪里开始在捕获组中搜索以替换空格。我甚至不知道我应该在网上搜索什么术语来试图找到答案 search = re.compile(r"\[(som
[something\u id='123'\u more-info='321']
迄今为止的产出:
{something\u id='123''u more-info='321'}
所需输出:
{something id='123'more info='321'}
我可以替换括号,但我不知道从哪里开始在捕获组中搜索以替换空格。我甚至不知道我应该在网上搜索什么术语来试图找到答案
search = re.compile(r"\[(something.*)\]")
return search.sub(r"{\1}", text_source)
如果这些文本包含在较长的文本中,请使用callable作为
re.sub
的替换参数:
重新导入
text\u source=''text[something\u id='123''u more-info='321']text…''
搜索=重新编译(r“\[(某物[^]]*]))
打印(search.sub(lambda x:f“{{{x.group(1).replace(''','''}}}}}”),文本\源)
#=>文本{something id='123'more info='321'}文本。。。
看
详细信息
匹配\[(something[^]]*]
,然后捕获[
,然后将something
以外的零个或多个字符捕获到组1中,然后匹配]
]
lambda x:f“{{{x.group(1).replace('''','''}}}”)将匹配传递给lambda,其中第1组文本用花括号括起,下划线用空格替换
- 请注意,f字符串中的文字大括号必须加倍
text_source=f“{{{{text_source.strip('[]').replace(''''',''}}}”
首先使用\[(something[^][*])]
从组1中获取方括号之间的内容,然后替换所有下划线的空格。可能f“{{{s.strip('[]')。replace('''',''}}}}”
?嘿,Wiktor,谢谢你的解释。是否有任何理由选择“[^]]*”而不是“*”?@alj[^]]
是一个否定字符类,最多只能匹配最接近的]
<代码>*太贪婪了。