Repetitions

Regular Expressions in Python

Maria Eugenia Inzaugarat

Data Science

Repeated characters

Validate the following string:

Regular Expressions in Python

Repeated characters

Validate the following string:

Regular Expressions in Python

Repeated characters

Validate the following string:

Regular Expressions in Python

Repeated characters

Validate the following string:

import re
password = "password1234"
re.search(r"\w\w\w\w\w\w\w\w\d\d\d\d", password)
<_sre.SRE_Match object; span=(0, 12), match='password1234'>
Regular Expressions in Python

Repeated characters

Validate the following string:

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

Quantifiers:

A metacharacter that tells the regex
engine how many times to match a
character immediately to its left.

Regular Expressions in Python

Quantifiers

  • Once or more: +

 

text = "Date of start: 4-3. Date of registration: 10-04."
re.findall(r"       ", text)
Regular Expressions in Python

Quantifiers

  • Once or more: +

 

text = "Date of start: 4-3. Date of registration: 10-04."
re.findall(r"\d+-   ", text)
Regular Expressions in Python

Quantifiers

  • Once or more: +

 

text = "Date of start: 4-3. Date of registration: 10-04."
re.findall(r"\d+-\d+", text)
['4-3', '10-04']
Regular Expressions in Python

Quantifiers

  • Zero times or more: *

 

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

re.findall(r"@\w+\W*\w+", my_string)
['@ameli!a', '@joh&&n', '@mary90']
Regular Expressions in Python

Quantifiers

  • Zero times or once: ?

 

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

re.findall(r"colou?r", text)
['color', 'colour']
Regular Expressions in Python

Quantifiers

  • n times at least, m times at most : {n, m}

 

phone_number = "John: 1-966-847-3131 Michelle: 54-908-42-42424"
re.findall(r"                          ", phone_number)
Regular Expressions in Python

Quantifiers

  • n times at least, m times at most : {n, m}

 

phone_number = "John: 1-966-847-3131 Michelle: 54-908-42-42424"
re.findall(r"\d{1,2}-                 ", phone_number)
Regular Expressions in Python

Quantifiers

  • n times at least, m times at most : {n, m}

 

phone_number = "John: 1-966-847-3131 Michelle: 54-908-42-42424"
re.findall(r"\d{1,2}-\d{3}-           ", phone_number)
Regular Expressions in Python

Quantifiers

  • n times at least, m times at most : {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']
Regular Expressions in Python

Quantifiers

  • Immediately to the left

    • r"apple+": + applies to e and not to apple
Regular Expressions in Python

Let's practice!

Regular Expressions in Python

Preparing Video For Download...