0

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

Oakley
  • 7
  • 2

1 Answers1

1

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")
sj95126
  • 6,520
  • 2
  • 15
  • 34
  • Thank you so much, I tried the try...except method originally but it didn't work for the float (I'm not quite sure why) but I had completely over done the Integer one, I have changed that to isdigit(). The fullmatch does work for the float though, but I've removed the need for another function which makes the code much easier to read (and probably slightly more memory efficient. Thank you again – Oakley Aug 13 '21 at 10:18