Backreferences

Regular expressions in Python

Maria Eugenia Inzaugarat

Data Scientist

Genummerde groepen

 

 

Regular expressions in Python

Genummerde groepen

 

Regular expressions in Python

Genummerde groepen

 

text = "Python 3.0 was released on 12-03-2008."
information = re.search(r'(\d{1,2})-(\d{2})-(\d{4})', text)

information.group(3)
'2008'
information.group(0)
'12-03-2008'
Regular expressions in Python

Benoemde groepen

  • Geef groepen een naam

 

Regular expressions in Python

Benoemde groepen

  • Geef groepen een naam
text = "Austin, 78701"

cities = re.search(r"(?P<city>[A-Za-z]+).*?(?P<zipcode>\d{5})", text)
cities.group("city")
'Austin'
cities.group("zipcode")
'78701'
Regular expressions in Python

Backreferences

  • Backreferences met capture-groepen

 

Regular expressions in Python

Backreferences

  • Backreferences met genummerde capture-groepen

 

sentence = "I wish you a happy happy birthday!"

re.findall(r"(\w+)\s ", sentence)
Regular expressions in Python

Backreferences

  • Backreferences met genummerde capture-groepen

 

sentence = "I wish you a happy happy birthday!"

re.findall(r"(\w+)\s\1", sentence)
['happy']
Regular expressions in Python

Backreferences

  • Backreferences met genummerde capture-groepen

 

sentence = "I wish you a happy happy birthday!"

re.sub(r"(\w+)\s\1", r"\1", sentence)
'I wish you a happy birthday!'
Regular expressions in Python

Backreferences

  • Backreferences met benoemde capture-groepen

 

sentence = "Your new code number is 23434. Please, enter 23434 to open the door."

re.findall(r"(?P<code>\d{5}).*?(?P=code)", sentence)
['23434']
Regular expressions in Python

Backreferences

  • Backreferences met benoemde capture-groepen

 

sentence = "This app is not working! It's repeating the last word word."
re.sub(r"(?P<word>\w+)\s(?P=word)", r"\g<word>", sentence)
'This app is not working! It's repeating the last word.'
Regular expressions in Python

Laten we oefenen!

Regular expressions in Python

Preparing Video For Download...