Mobile Number validation with Python
Hi Friends in this article we will discuss validating a mobile number with Python.
For the understanding purpose, we are going to validate a mobile number with a length of 10 digits only.
Example: 78*****45**
Mobile Number validation criteria
- The first digit should contain numbers between 6 to 9.
- The rest 9 digits can contain any number between 0 to 9.
Coding part
For the coding part, we are going to use Python. In Python, we have a module called re module which can be used for pattern matching.
- Now import ‘re’ module
- To validate the mobile number we need to use a function fullmatch from the re module
- Fulllmatch is a function that takes two inputs i.e. one input for the pattern and the other for the string validation
- It returns a match object if and only if the entire string matches the pattern else it returns None
- Depending on the return value we can decide whether it is a valid number or not.
- We can write various pattern for the same validation of string. For this number validation, I will show some methods
- ‘[6-9][0-9]{9}’ . This is simple which says that the starting should be between 6-9 and the next nine digits can be anything between 0-9.
- ‘[6-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]’. This pattern also works as similar to the above pattern.
import re # Importing re module n=input('Enter Mobile number :') # Reading input from the user r=re.fullmatch('[6-9][0-9]{9}',n) # calling fullmatch function by passing pattern and n if r!=None: # checking whether it is none or not print('Valid Number') else: print('Not a valid number')
Output:
Enter Mobile number: 781111111
Valid Number
For better understanding:
- For a better understanding of re module, click here
- For a better understanding of the full match function, clickhere
Leave a Reply