Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

A set is a set of characters inside a pair of square brackets [] with a special meaning:

The following are code examples demonstrating the use of sets in regular expressions:

“`python
import re

# [arn]: Returns a match where one of the specified characters (a, r, or n) is present
pattern = r'[arn]’
test_string = “The quick brown fox jumps over the lazy dog.”

matches = re.findall(pattern, test_string)
print(“Matches for [arn]:”, matches)

# [a-n]: Returns a match for any lower case character, alphabetically between a and n
pattern = r'[a-n]’
test_string = “The quick brown fox jumps over the lazy dog.”

matches = re.findall(pattern, test_string)
print(“Matches for [a-n]:”, matches)

# [^arn]: Returns a match for any character EXCEPT a, r, and n
pattern = r'[^arn]’
test_string = “The quick brown fox jumps over the lazy dog.”

matches = re.findall(pattern, test_string)
print(“Matches for [^arn]:”, matches)

# [0123]: Returns a match where any of the specified digits (0, 1, 2, or 3) are present
pattern = r'[0123]’
test_string = “The price is $20.99.”

matches = re.findall(pattern, test_string)
print(“Matches for [0123]:”, matches)

# [0-9]: Returns a match for any digit between 0 and 9
pattern = r'[0-9]’
test_string = “The price is $20.99.”

matches = re.findall(pattern, test_string)
print(“Matches for [0-9]:”, matches)

# [0-5][0-9]: Returns a match for any two-digit numbers from 00 and 59
pattern = r'[0-5][0-9]’
test_string = “The time is 12:34.”

matches = re.findall(pattern, test_string)
print(“Matches for [0-5][0-9]:”, matches)

# [a-zA-Z]: Returns a match for any character alphabetically between a and z, lower case OR upper case
pattern = r'[a-zA-Z]’
test_string = “The quick brown fox jumps over the lazy dog.”

matches = re.findall(pattern, test_string)
print(“Matches for [a-zA-Z]:”, matches)

# [+]: In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for any + character in the string
pattern = r'[+]’
test_string = “The price is $20.99.”

matches = re.findall(pattern, test_string)
print(“Matches for [+]:”, matches)
“`

These examples demonstrate how to use sets in regular expressions to match specific characters or ranges of characters within text data.

Join the conversation