Search code examples
pythonregexfiltercompilationtextinput

Allowing only float numbers, with one decimal point, AND A NEGATIVE SIGN (Python/Kivy/Regex)


Firstly, I would like to say I'm very new to the language, but already got pretty deep in my calculator app for simple physics equations. My plan is to make a home screen with one other calculation screen first, and once that is as good as I can get it to be, I will continue to the rest of the screens.

In this particular screen, (and probably most other ones I'll have to use this function) I've established a custom TextInput that only allows numbers 0-9 and one decimal point. However, I'm currently breaking my head trying to figure out how to include a NEGATIVE SIGN in to my allowed set of inputs.

Here's the code: (I found it open source, I understand the logistics, but I've yet to completely understand the re.compile function)

class FloatInput(TextInput):

    pat = re.compile('[^0-9]') <----THIS IS WHERE I TRIED TO ADD ^[+-]? w/ NO LUCK :(
    def insert_text(self, substring, from_undo=False):

        pat = self.pat

        if '.' in self.text:
            s = re.sub(pat, '', substring)


        else:
            s = '.'.join([re.sub(pat, '', s) for s in substring.split('.', 1)])


        return super(FloatInput, self).insert_text(s, from_undo=from_undo)

Solution

  • From the Python doc'n for the re module:

    If - is escaped (e.g. [a\-z]) or if it’s placed as the first or last character (e.g. [-a] or [a-]), it will match a literal '-'.

    To get a pattern that matches anything but 0-9, - or +, you can use

    pat = re.compile('[^0-9\-+]')