简体   繁体   English

替换捕获组中的多个字符

[英]Replacing multiple characters in a capturing group

I need to replace the square brackets for curly brackets and the underscores for spaces.我需要替换大括号的方括号和空格的下划线。

Input: [something_id='123'_more-info='321']输入: [something_id='123'_more-info='321']

Output so far: {something_id='123'_more-info='321'} Output 到目前为止: {something_id='123'_more-info='321'}

Required Output: {something id='123' more-info='321'}需要 Output: {something id='123' more-info='321'}

I can replace the brackets but I don't know where to start with searching within the capturing group to replace the spaces.我可以替换括号,但我不知道从哪里开始在捕获组中搜索以替换空格。 I'm not even sure what terms I should be searching the web for to try to find the answer.我什至不确定我应该在 web 中搜索哪些术语来尝试找到答案。

search = re.compile(r"\[(something.*)\]")
return search.sub(r"{\1}", text_source)

If you have these texts inside longer texts, use a callable as the replacement argument to re.sub :如果您在较长的文本中包含这些文本,请使用可调用对象作为re.sub的替换参数:

import re
text_source = '''Text [something_id='123'_more-info='321'] Text...'''
search = re.compile(r"\[(something[^]]*)]")
print( search.sub(lambda x: f"{{{x.group(1).replace('_', ' ')}}}", text_source) )
# => Text {something id='123' more-info='321'} Text...

See the Python demo .请参阅Python 演示

Details细节

  • \[(something[^]]*)] matches [ , then captures something and then zero or more chars other than ] into Group 1 and then matches ] \[(something[^]]*)]匹配[ ,然后捕获something ,然后将]以外的零个或多个字符放入第 1 组,然后匹配]
  • lambda x: f"{{{x.group(1).replace('_', ' ')}}}" - the match is passed to the lambda where Group 1 text is enclosed with curly braces and the underscores are replaced with spaces lambda x: f"{{{x.group(1).replace('_', ' ')}}}" - 匹配传递给 lambda,其中第 1 组文本用大括号括起来,下划线被替换有空格
  • Note that literal curly braces inside f-strings must be doubled.请注意,f 字符串中的文字大括号必须加倍。

If the strings are standalone strings, all you need is如果字符串是独立字符串,则您只需要

text_source = f"{{{text_source.strip('[]').replace('_', ' ')}}}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM