alj
alj

Reputation: 3039

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)

Upvotes: 2

Views: 73

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

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('_', ' ')}}}"

Upvotes: 1

Related Questions