後方参照

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で学ぶ正規表現

練習しましょう!

Pythonで学ぶ正規表現

Preparing Video For Download...