How to check if a string is in a valid format ("XXX-XXX-XXXX") with numbers in Python

1 Answer

0 votes
import re

def is_valid_format(s):
    pattern = r'^(\d{3}-)?\d{3}-\d{4}$'
    
    if re.match(pattern, s):
        return True
        
    return False

s = "771-290-1652"
if is_valid_format(s):
    print("Valid")
else:
    print("Not Valid")

s = "771-29-162"
if is_valid_format(s):
    print("Not Valid")
else:
    print("Not Valid")

s = "771-Xz8-1620"
if is_valid_format(s):
    print("Not Valid")
else:
    print("Not Valid")
    
    
    
'''
run:

Valid
Not Valid
Not Valid

'''

 



answered Nov 16, 2024 by avibootz
...