Python - Regular Expressions
Python - Regular Expressions
EXPRESSIONS
REGULAR EXPRESSIONS
• Regular expressions, often shortened to regex or regexp, are
sequences of characters that define a search pattern.
• They are a powerful tool for matching text based on predefined
patterns.
• Eg: 1) [abc] will match characters a,b and c in any string.
2) The regular expression ab+c will give abc, abbc, abbbc, … and so
on.
REGULAR EXPRESSION IN PYTHON
• implemented through the built-in re module.
• Import the re module: import re
• When you have imported the re module, you can start using regular
expressions.
• Raw Strings: It is common practice to use raw strings (prefixed with r
or R) for regular expression patterns to prevent backslashes from
being interpreted as escape sequences by Python.
Eg: pattern = r"^[1-9][0-9]{5}$" # Matches pin number
Program to validate 6 digit pin
number
import re
pin=input("Enter pin")
pattern=r"^[1-9][0-9]{5}$"
if re.fullmatch(pattern, pin):
print(f"{pin} → Valid PIN")
else:
print(“Invalid pin”)
RE functions
• Core Functions: The re module provides various functions for working
with regular expressions:
Sl. Functin Meaning
No:
1 re.search(pattern, string): Scans through a string looking for the first location where the pattern produces a
match. Returns a match object if found, None otherwise
2 re.match(pattern, string): Checks for a match only at the beginning of the string. Returns a match object if found,
None otherwise.
3 re.findall(pattern, string): Returns a list of all non-overlapping matches in the string.
4 re.sub(pattern, repl, string): Replaces all occurrences of the pattern in the string with repl.
5 re.split(pattern, string): Splits the string by occurrences of the pattern.
6 re.compile(pattern): Compiles a regular expression pattern into a regular expression object, which can be
used for more efficient repeated matching
• Example:
import re
string = "Hello my Number is 123456789 and my friend's number is
98799999"
regex = '\d+'
match = re.findall(regex, string)
print(match)
import re
# Checking if the string starts with a number
s = "123abc"
match = re.match(r"\d", s) # \d means any digit
if match:
print("Starts with a number.")
else:
print("Doesn't start with a number.")
• write a Python program to validate email addresses that must end
with @sjcetpalai.ac.in only using regular expressions?
• Eg: abcd2025#@sjcetpalai.ac.in