Search code examples
pythonpython-re

Is there a way to check if every character in a string conforms to the set RE conditions?


I've been re-learning python over the last 2 days, and decided to use regular expression [here out referred to as RE] for the first time (in conjunction with tkinter), its exceptionally confusing.

I'm trying to check every character in a string is a number or period, however this has proven difficult for me to wrap my head around.

Here is the code:

def matchFloat(string, search=re.compile(r'[0-9.]').search):
    return bool(search(string))

def matchInt(string, search=re.compile(r'[0-9]').search):
    return bool(search(string))

def callbackFloat(P):
    if matchFloat(P) or P == "":
        return True
    else:
        return False

def callbackInt(P):
    if matchInt(P) or P == "":
        return True
    else:
        return False

The first character entered into my enter box [see below] is forced to be a number or . (in the Floats case), however RE search() only requires 1 of the characters to meet the conditions for it to return True. So in short, Is there a way to only return True if every character in a string conforms to the set RE conditions?

Any help is appreciated, thank you in advanced!

Images: As you can see, I'm quite new to this. Disallowed Characters In Box


Solution

  • This thread may be helpful as it covers the topic of tkinter input validation.

    However, quick answer to your question:

    search(r"^[0-9]+$", string)
    

    would match an integer string. The RE pattern means "one or more digits, extending from the beginning of the string to the end". This can also be shortened to r"^\d+$".

    You could also use the re.fullmatch() method:

    fullmatch(r"[0-9]+", string)
    

    And for the sake of completeness, I'll point out that you don't need to do this work yourself. You can determine if a string represents an integer with string.isdigit(), string.isdecimal(), or string.isnumeric() methods.

    As for checking whether a string is a float, the Pythonic way is to just try converting to a float and catch the exception if it fails:

    try:
        num = float(string)
    except:
        print("not a float")