重复

Python 中的正则表达式

Maria Eugenia Inzaugarat

Data Science

字符重复

验证以下字符串:

Python 中的正则表达式

字符重复

验证以下字符串:

Python 中的正则表达式

字符重复

验证以下字符串:

Python 中的正则表达式

字符重复

验证以下字符串:

import re
password = "password1234"
re.search(r"\w\w\w\w\w\w\w\w\d\d\d\d", password)
<re.Match object; span=(0, 12), match='password1234'>
Python 中的正则表达式

字符重复

验证以下字符串:

import re
password = "password1234"
re.search(r"\w{8}\d{4}", password)
<re.Match object; span=(0, 12), match='password1234'>

量词:

元字符,用于指示正则引擎匹配其左侧字符的次数。

Python 中的正则表达式

量词

  • 至少一次:+

 

text = "Date of start: 4-3. Date of registration: 10-04."
re.findall(r"       ", text)
Python 中的正则表达式

量词

  • 至少一次:+

 

text = "Date of start: 4-3. Date of registration: 10-04."
re.findall(r"\d+-   ", text)
Python 中的正则表达式

量词

  • 至少一次:+

 

text = "Date of start: 4-3. Date of registration: 10-04."
re.findall(r"\d+-\d+", text)
['4-3', '10-04']
Python 中的正则表达式

量词

  • 零次或多次:*

 

my_string = "The concert was amazing! @ameli!a @joh&&n @mary90"

re.findall(r"@\w+\W*\w+", my_string)
['@ameli!a', '@joh&&n', '@mary90']
Python 中的正则表达式

量词

  • 零次或一次:?

 

text = "The color of this image is amazing. However, the colour blue could be brighter."

re.findall(r"colou?r", text)
['color', 'colour']
Python 中的正则表达式

量词

  • 至少 n 次,至多 m 次:{n, m}

 

phone_number = "John: 1-966-847-3131 Michelle: 54-908-42-42424"
re.findall(r"                          ", phone_number)
Python 中的正则表达式

量词

  • 至少 n 次,至多 m 次:{n, m}

 

phone_number = "John: 1-966-847-3131 Michelle: 54-908-42-42424"
re.findall(r"\d{1,2}-                 ", phone_number)
Python 中的正则表达式

量词

  • 至少 n 次,至多 m 次:{n, m}

 

phone_number = "John: 1-966-847-3131 Michelle: 54-908-42-42424"
re.findall(r"\d{1,2}-\d{3}-           ", phone_number)
Python 中的正则表达式

量词

  • 至少 n 次,至多 m 次:{n, m}

 

phone_number = "John: 1-966-847-3131 Michelle: 54-908-42-42424"
re.findall(r"\d{1,2}-\d{3}-\d{2,3}-\d{4,}", phone_number)
['1-966-847-3131', '54-908-42-42424']
Python 中的正则表达式

量词

  • 作用于"左侧紧邻"的字符

    • r"apple+"+ 作用于 e,而非整个 apple
Python 中的正则表达式

Passons à la pratique !

Python 中的正则表达式

Preparing Video For Download...