Python Solution with Regular Expression

  • 0

    We can split the Valid Number String into 5 parts:

    • Part 1: The \s*, 0 or mang blank spaces.

    • Part 2: A integer number with '+', '-' or nothing.

    • Part 3: A point '.' with numbers.

    • Part 4: 'e' with numbers with '+', '-' or nothing, Used in scientific notation.

    • Part 5: The \s*, 0 or mang blank spaces.

    and, Part 2 and Part 3 can't be empty simultaneously.
    So, We got the regular expression:
    reg = "\s*[+,-]?(([0-9]+(.[0-9])?)|([0-9](.[0-9]+){1}))(e[+,-]?[0-9]+)?\s*"
    and our code:

    import re
    class Solution(object):
        def isNumber(self, s):
            :type s: str
            :rtype: bool
            reg = "\s*[+,-]?(([0-9]+(\.[0-9]*)?)|([0-9]*(\.[0-9]+){1}))(e[+,-]?[0-9]+)?\s*"
            m = re.match(reg, s)
            if m :
                return len( == len(s)
            else :
                return False 

  • 0

    Instead of comparing length of matched strings you could require your regex to only match all string or don't match at all.


    Here ^ stands for begin of string, and $ for its end.

    I got also confused by the fact that 43.e3 should have passed. In scientific notation fraction is usually normalized to be between 1 and 10.

Log in to reply

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