Regex Pattern Matching Examples
Code # 01
Pakistan Mobile Number Pattern
pattern = r'^[+92]+[3]+[0-4]+[0-9]{8}$'
text = "+923212345678"
m=re.match(pattern,text)
if m:
print("Pattern Matched")
else:
This code is checking whether the given phone number is a valid Pakistan phone number. The pattern is defined as follows:
- The phone number must start with "+92" ,
- After +93 digit must be either 3.
- The third digit is Sim Code must be any numeric digit from 0 to 4.
- The remaining eight digits must be any numeric digit from 0 to 9.
Code # 02:
Pakistan ID Card Pattern
This is a Python code snippet that uses the re module to check whether a given string matches the pattern for a Pakistani National Identification Card (NIC) number.The pattern is defined as follows:
- The string must start with exactly 5 digits, represented by the character class [0-9]{5}.
- This must be followed by a hyphen, represented by the character class [-]+.
- The next 7 characters must be exactly digits, represented by the character class [0-9]{7}.This must be followed by a hyphen [-]+
- The last character must be exactly 1 digit, represented by the character class [0-9]{1}.
Note: that while this pattern matches strings that have the correct format for a Pakistani NIC number, it does not check whether the given NIC number is actually valid or not, as the check digit calculation algorithm is more complex
Code # 03:
Date Pattern
This regular expression pattern matches date strings in the format "DD/MM/YYYY". Here's how the pattern works:
- ^ matches the start of the string
- (0[0-9]|[12][0-9]|3[01]) matches the day component, which can be "01" to "09", "10" to "29", "30", or "31"
- / matches the delimiter between the day and month components
- (0[0-9]|1[0-2]) matches the month component, which can be "01" to "09" or "10" to "12"
- / matches the delimiter between the month and year components
- [0-9]{4} matches the year component, which consists of four digits
- $ matches the end of the string
So the pattern as a whole matches a string that consists of a valid date in the specified format. In your code snippet, the pattern is used to match the date string "13/04/2023", and since it matches the pattern, the output will be "Pattern Matched". Otherwise print "Pattern Not Match".
LIKE SHARE AND SUBSCRIBE 👈👇👇👇