简体   繁体   中英

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']

Output so far: {something_id='123'_more-info='321'}

Required 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.

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 :

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 .

Details

  • \[(something[^]]*)] matches [ , then captures something and then zero or more chars other than ] into Group 1 and then matches ]
  • 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
  • Note that literal curly braces inside f-strings must be doubled.

If the strings are standalone strings, all you need is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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