Home > Enterprise >  Facing issue while validating special phone number using regex in python
Facing issue while validating special phone number using regex in python

Time:01-13

You are given a number input, and need to check if it is a valid phone number. A valid phone number has exactly 8 digits and starts with 1, 8 or 9. Output "Valid" if the number is valid and "Invalid", if it is not.

Sample Input 81239870

Sample Output Valid

Here is my code

import re


def isValid(s): 
    Pattern = re.compile("(^1|^8|^9)[0-9]{7}")
    return Pattern.match(s) 
    
s = input()
if (isValid(s)): 
    print ("Valid")
else : 
    print ("Invalid")

This is working fine for most numbers but not for few.

CodePudding user response:

I got this, I think it works but I do not see why your code should fail? Maybe add $ to show that is the end of the line.

^[1|8|9]\d{7}$

In a function:

def isValid(s):
    pattern = re.compile(r'^[1|8|9]\d{7}$')
    if pattern.search(s):
        return 'Valid'
    return 'Invalid'
isValid('12345678')
>>> 'Valid'
isValid('22345678')
>>> 'Invalid'

CodePudding user response:

import re


def isValid(s):
    Pattern = re.compile("^(1|8|9)[0-9]{7}$")
    return Pattern.match(s)


s = input()
if (isValid(s)):
    print("Valid")
else:
    print("Invalid")

Verified with sample input:

  1. 12345678 -> Valid
  2. 98765432 -> Valid
  3. 08765431 -> Invalid
  4. 8578 -> Invalid

You can also use pattern: ^[189][0-9]{7}$

Demo: regexr.com/6d84r

CodePudding user response:

re.match() will start matching from the start-line anchor (or rather leftmost position). With your current pattern you'll even find that '899999999999999999999999999' is a valid number.

Either use:

  • re.match() - And use the end-line anchor;
  • re.fullmatch() - To ensure the whole string is matched.

A valid re-written pattern will be [189]\d{7} where both options will start matching from the leftmost character, but you'd need an additional end-line anchor if you choose to keep using re.match() >> [189]\d{7}$.

Therefor working code could be:

def isValid(s): 
    Pattern = re.compile("[189]\d{7}")
    return Pattern.fullmatch(s)

Or:

def isValid(s): 
    Pattern = re.compile("[189]\d{7}$")
    return Pattern.match(s)

A subtle difference but it will prevent false positives. Other than that, your code seems fine.

CodePudding user response:

You did not use $ to denote end, so (^1|^8|^9)[0-9]{7} will also match numbers starting with 1 or 8 or 9 and having more than 8 digits. for example

1000000000

Either add $ to denote end that is change (^1|^8|^9)[0-9]{7} to (^1|^8|^9)[0-9]{7}$ or use fullmatch function (requires python3.4 or newer) rather than match, in which case ^ are no longer needed, so it is sufficient to do

Pattern = re.compile("(1|8|9)[0-9]{7}")
return Pattern.fullmatch(s) 
  •  Tags:  
  • Related