Why do the same Pattern,sub and findall find different results?

question: for string= "jsfd {sdf} df", I want to extract the sdf into "jsfd {} df".
uses patten = re.compile (r "{(. *?)}"), but finds that findall will find sdf, and finditer or sub will match {sdf}. I don"t know why? When will the regular match the parentheses on both sides?

The

problem itself has been solved with patten = re.compile (r"(? < = {). *? (?)), but it"s curious why findall matches finditer and sub differently.


findall is returned first by grouping, and if there is no grouping, the entire expression is returned.
finditer or sub takes precedence over the whole expression, finditer can handle grouping separately, and sub can specify to replace certain groupings.


the answer on the first floor is correct:

findall is returned first by grouping, and if there is no grouping, the entire expression is returned.
finditer or sub takes precedence over the whole expression, finditer can handle grouping separately, and sub can specify to replace certain groupings.

the following example is shown:

import re

string="jsfd{sdf}{}df"
patten = re.compile(r"{(.*?)}")
-sharpfindall
print("",patten.findall(string))
for m in patten.finditer(string):
    -sharpfinditerre.Match object
    print("finditer-->",m)
    -sharp
    print("-->",m.group())
    -sharp
    print("-->",m.groups())

print("*"*30)
-sharpsub
def change(world):
    -sharpsubfinditerre.Match object
    print(world)
    -sharp 
    print("-->", m.group())
    -sharp 
    print("-->", m.groups())
    return ""
print(":",re.sub(patten,change,string))

run result:

 ['sdf', '']
finditer--> <re.Match object; span=(4, 9), match='{sdf}'>
--> {sdf}
--> ('sdf',)
finditer--> <re.Match object; span=(9, 13), match='{}'>
--> {}
--> ('',)
******************************
<re.Match object; span=(4, 9), match='{sdf}'>
--> {}
--> ('',)
<re.Match object; span=(9, 13), match='{}'>
--> {}
--> ('',)
: jsfddf

reference:
Python practical techniques part 23: regular: text pattern matching and searching Python practical techniques part 24: regular: finding and replacing text
Python practical techniques part 25: regular: finding and replacing text in a case-insensitive manner

Menu