Regular Expression
Pattern Matching In Python
What is pattern matching in Python?
Pattern matching in Python is a feature introduced in version 3.10 that allows you to match specific patterns of data in complex data structures using the match statement, simplifying conditional statements and reducing the amount of boilerplate code needed.
How we import regex/regular expression Library?
The re library in Python is a module that provides support for regular expressions. It allows you to work with regular expressions in Python code, allowing you to match patterns in strings, replace substrings in a string, and perform other operations using regular expressions.
Import Library
import re
Patterns Creation
^[a-z]*$ accept all small letters
^[0-9]*$ accept all digits
The ^ and $ characters at the beginning and end of the pattern indicate that the pattern must match the entire string
Match Pattern With Strings
1). Name Pattern
^[A-Z][a-z]*$ or ^[A-Za-z]*$
Code:
pattern = r'^[A-Z][a-z]*$'
string = 'Arsalan'
print(re.match(pattern,string))
2). Gmail Pattern
^[a-z0-9]+@gmail.com*$
Code:
pattern = r"^[a-z0-9]+@gmail.com*$"
string = "arsalan@gmail.com"
print(re.match(pattern,string))
I). ^[+92]+[3]+[0-4]{1}+[0-9]{8}$
pattern = r"^[+92]+[3]+[0-4]{1}+[0-9]{8}$"
string = "+92321234567"
print(re.match(pattern,string))
pattern = r"^[03]+[0-4]{1}+[0-9]{8}$"
string = "03321234567"
print(re.match(pattern,string))
r is nothing but it is a prefix of regular expression.