Simple one line regex solution

  • 10
    • The integer RE is: ^[+-]?\d+$
    • The float RE is: ^[+-]?((\d*\.\d+)|(\d+\.\d*))$
    • The scientific notation RE is: ^[+-]?((\d*\.\d+)|(\d+(\.\d*)?))[eE][+-]?\d+$

    We can combine them as one: ^[+-]?((\d*\.\d+)|(\d+(\.\d*)?))([eE][+-]?\d+)?$

    class Solution(object):
        regex = re.compile(r'^[+-]?((\d*\.\d+)|(\d+(\.\d*)?))([eE][+-]?\d+)?$')
        def isNumber(self, s):
            return bool(self.regex.match(s.strip()))

  • -1



Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.