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

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b32bc8-2b385.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b32bc8-2b385.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?