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

re get text between braces

Data

module All
{

    obj Bucket
    {
        Damage = 900
        Type = Weapon
        Cooldown = 2
        Craftable = false
    }
}

Output

"Bucket": {
    Damage: 900
    Type: Weapon
    Cooldown: 2
    Craftable: false
}

Current Code

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

def get_object(x):
    pattern = r'\{+(.*?)\}'
    
    return re.findall(pattern, x, re.MULTILINE) # returns []

I want to get the data between the { }, this code works for eg. "{ text }" but not for this string, maybe it’s because of the newlines, I don’t know much regex so any help is appreciated!

>Solution :

Use this pattern

(?<=obj\s)(\w+)(?:.*?)(\{.*?\})

Also, see the demo

Python Example

import re

text = """module All
{

    obj Bucket
    {
        Damage = 900
        Type = Weapon
        Cooldown = 2
        Craftable = false
    }
}"""

result = re.search(r"(?<=obj\s)(\w+)(?:.*?)(\{.*?\})", text, re.S)
if result:
    key, value = result.groups()
    print(f'"{key}": {value}')

Output

"Bucket": {
        Damage = 900
        Type = Weapon
        Cooldown = 2
        Craftable = false
    }
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