Python Regex captures only specific text

I am trying to find functionality in python similar to checking Ruby function. My goal is to capture all text between two curly braces in a list. If there are several pairs of curly braces in a line, I want to have several entries in the list.

When I run this code:

match = re.search(r'\{(.+)\}', request.params['upsell']) print match.group() 

I agree with the correct text. However, what is captured includes braces. I do not want to include this text, I want to include everything in between, but not curly braces Thank you!

+6
source share
3 answers
 re.findall(r'\{(.+?)\}', request.params['upsell']) 

This will return a list in which each entry represents the contents of another group of curly braces. Note that this will not work for nested braces.

? after .+ will make him lazy (as opposed to greedy). This means that the match will stop at the first "}", instead of continuing to match as many characters as possible and ending with the last closing bracket.

re.findall() will search your string and find all matching matches and return the group. Alternatively, you can use re.finditer() , which will re.finditer() over Match objects, but then you will need to use match.group(1) to get only what is inside the curly braces. This is also what you will need to change in your example, match.group() returns a complete match, not a captured group, for this you need to put the number for the group you need.

+9
source

Use group(1) , or lookbehinds / ahead. (Also, be sure to refer to FJ and JF and use either .+? Or [^{}]*

 import re match = re.search(r'\{(.+)\}', "asdfasd {asdf}asdfasdf") print match.group(1) 

or with lookbehinds / ahead:

 import re match = re.search(r'(?<=\{)(.+)(?=\})', "asdfasd {asdf}asdfasdf") print match.group() 
+9
source
 >>> import re >>> re.findall(r'{([^{}]*)}', '{a} { {b} c { {d} } }') ['a', 'b', 'd'] 
+1
source

Source: https://habr.com/ru/post/897718/


All Articles