Using regex to see if a number is in a string before others?

Viewed 80

I am new to python, so obviously as well to using regex. I am just curious if it is possible to see if a number is inputted before other numbers in a string?

What this function(def checkzero) should be doing is checking to see if 0 is inputted before another number, and if it is then return True (For invalid)

import string
import re

plate_pattern = re.compile('\D*\d*')


def main():
    plate = input("Plate: ")
    tests = [exclusions, platecheck, checkzero]
    invalid = any(test(plate) for test in tests)
    if invalid:
        print("Invalid \nNo numbers in the start/middle of the plate, first number may not be 0. \nNo punctuation allowed.\nPlate must be between 2-6 characters.")
    else:
        print("Valid")


def exclusions(s):
    if any(c in string.punctuation for c in s):
        return True
    return len(s) > 6 or len(s) < 2


def platecheck(s):
    return not plate_pattern.fullmatch(s)


def checkzero(s):
    # Not sure how to go about creating the function to check if zero is inputted before other numbers.
    pass


main()

Example of Input/Output:

Input:

test02

Output:

Invalid
...

Input:

test20

Output:

Valid
2 Answers

So to make it simple, we are just checking, if first occurence of a digit in given string is 0 or not.

import re

def checkzero(s):
    return re.search(r'\d', s).group() == '0'

Test:

test_cases = ['test0', 'test02', 'test20', 'test002', 'test2022']
for test_case in test_cases:
    print(checkzero(test_case))

Output:

>>> True
>>> True
>>> False
>>> True
>>> False

Revision in response to comment

The first number at any point can not be 0

You could look from the start of the string ^ for non-digit characters [^\d]* and then a 0 perhaps followed by a digit .*\d?, then proceed the same from there (also updated test cases):

def checkzero(s):
    p = re.compile(r"^[^\d]*0.*\d?")
    matched = re.search(p, s)
    return re.search(p, s) != None
    
test_cases = ["test0", "test1", "test01", "test10", "test101"]

for test in test_cases:
    print(test, end = ": ")
    if checkzero(test):
        print("Matched, INVALID")
    else:
        print("Not matched, VALID")```

Output:

test0: Matched, INVALID
test1: Not matched, VALID
test01: Matched, INVALID
test10: Not matched, VALID
test101: Not matched, VALID

Original Post

You could use re.search(). If a match is found, then a Match object will be returned, otherwise None will be returned.

def checkzero(s):
    p = re.compile(r"0.*\d")
    matched = re.search(p, s)
    return re.search(p, s) != None

Note: if you want the 0 to be immediately followed by a digit, remove the .* in the regex expression

Related