反向引用

Python 中的正则表达式

Maria Eugenia Inzaugarat

Data Scientist

编号分组

 

 

Python 中的正则表达式

编号分组

 

Python 中的正则表达式

编号分组

 

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'
Python 中的正则表达式

命名分组

  • 为分组命名

 

Python 中的正则表达式

命名分组

  • 为分组命名
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'
Python 中的正则表达式

反向引用

  • 使用捕获组进行反向引用

 

Python 中的正则表达式

反向引用

  • 使用编号捕获组进行反向引用

 

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

re.findall(r"(\w+)\s ", sentence)
Python 中的正则表达式

反向引用

  • 使用编号捕获组进行反向引用

 

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

re.findall(r"(\w+)\s\1", sentence)
['happy']
Python 中的正则表达式

反向引用

  • 使用编号捕获组进行反向引用

 

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

re.sub(r"(\w+)\s\1", r"\1", sentence)
'I wish you a happy birthday!'
Python 中的正则表达式

反向引用

  • 使用命名捕获组进行反向引用

 

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']
Python 中的正则表达式

反向引用

  • 使用命名捕获组进行反向引用

 

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.'
Python 中的正则表达式

Passons à la pratique !

Python 中的正则表达式

Preparing Video For Download...