Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can python extract text within repeated specific characters?

Is it possible to extract text contained in a specific character set {} when it is repeated multiple times in the string?

string = 'Revenue for the period is {value="32", font="34"} and EBITDA is {value="12", font="34"} for 2022'

The output should contain the instances as elements in a list in string format.

output = ['{value="32", font=34}', '{value="12", font=34}']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use re to apply a regex pattern to match text in curly brackets:

import re

# Dont use str (a built-in class) as a variable name
string = 'Revenue for the period is {value="32", font="34"} and EBITDA is {value="12", font="34"} for 2022'

output = re.findall(r'{[^}]+}', string)
>>> output
['{value="32", font="34"}', '{value="12", font="34"}']

Note that output will be an empty list if there are no matches

Online demo: https://regex101.com/r/XB7U9g/1

My reccomendation for learning regex patterns: https://regexone.com/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading