Python Regex Match Leading Space, starting-text and Everything inside Curly Braces

Viewed 131

I am new to regex and I want some suggestion for my code please. I have the following code in python:

import re

textToSearch = """ 
hello{
    @hi {
        I want this text
    }

    @hola {
        I don't want this text
    }
} 
"""

regex= r'(?<=@hi {)[^}]*'
result = re.findall(regex,textToSearch)

print(result) 

#Output = ['\n I want this text\n ']

What I want as a output is:

@hi { #everything in here }

including leading space and curly braces of @hi

I would appreciate any suggestion to solve this. Thank you.

3 Answers

You can include hi in the match instead of asserting it to the left, and match spaces without newlines using [^\S\r\n]*.

If you also want to match the leading newlines, you can use \s*

[^\S\r\n]*@hi\b[^\S\r\n]*{[^{}]*}

See a regex demo and a Python demo

The pattern matches:

  • [^\S\r\n]* Match 0+ whitespace chars without a newline
  • @hi\b Match @hi
  • [^\S\r\n]* Match 0+ whitespace chars without a newline
  • {[^{}]*} Match from { till } using a negated character class matching any char (include matching newlines) except the curly's

For example

import re

textToSearch = """ 
hello{
    @hi {
        I want this text
    }

    @hola {
        I don't want this text
    }
} 
"""

regex= r'[^\S\r\n]*@hi\b[^\S\r\n]*{[^{}]*}'
result = re.findall(regex,textToSearch)

print(result) 

Output

['    @hi {\n        I want this text\n    }']

You can use this regex pattern to match your text :

pattern = r'@hi \{\n\s+(?P<text>[\w ]+)\n\s+\}'
match_result = re.search(pattern, textToSearch)

# To get all the found value
match_found = match_result.group(0)

# To get the text only
needed_text = match_result['text']

print(match_found)
print(needed_text)

Here is the explanation of the pattern :

  • \n for newline
  • \s for space
  • \w for alpanumeric
  • (?P<group_name>[pattern_value]) for a group seach
  • + for one or more value

Using regex flags to expand meaning of ^ and . you can use this pattern:

import re

textToSearch = """ 
hello{
    @hi {
        I want this text
    }

    @hola {
        I don't want this text
    }
} 
"""

# regex = '(?sm)^\s*@hi\s*{.*?}'  # non-verbose version

regex= r'''(?smx)  # DOTALL|MULTILINE|VERBOSE flags
           ^       # start of line (due to MULTILINE)
           \s*     # any amount of whitespace
           @hi     # match exactly these characters
           \s*     # any amount of whitespace
           {.*?}   # capture everything up between braces (due to DOTALL)
        ''' 

result = re.findall(regex,textToSearch)
print(result) 

Output:

['    @hi {\n        I want this text\n    }']
Related