DEV Community

loading...

Valid Number

jpantunes profile image JP Antunes ・2 min read

The valid number problem currently has the lowest acceptance rate of Leetcode at just 14.9%. That must mean it's hard right?

This one reminded me of my Perl days because somehow it's 3 AM and I'm having fun with regular expressions :-)

/**
 * @param {string} s
 * @return {boolean}
 */
var isNumber = function(s) {

  const trimRegex = /(^\s+|\s+$)/g;
  const trimedS = s.replace(trimRegex, '')
  if (trimedS.length == 0) return false;

  const validCharsRegex = /[0-9e+-.]/;
  if (![...trimedS].every(e => e.match(validCharsRegex))) return false;

  const invalidPatternsRegex = /(^\.e|^\.$|^e.*?|e.+?\.+?|\..+?\.|.+?e$|\d+?[+-]\d.?|[+-]+?\.$|.+?[+-]$|.+?e+?.*?e+?|\+[e+-]+?|\-[e+-]+?|\.[.+-]+?|e\.+?)/gi;
  if (trimedS.match(invalidPatternsRegex)) return false;

  return true;
};

Short, and hopefully correct description of the scary regex:

const invalidPatternsRegex = /
    (^\.e               -> . at the beginning of string followed by e
    |^\.$               -> only 1 .
    |^e.*?              -> e at the beginning of string followed by any zero or more times
    |e.+?\.+?           -> e 1 or more times followed by . 1 or more times
    |\..+?\.            -> . followed by any 1 or more times followed by .
    |.+?e$              -> any 1 or more times followed by e at the end of string
    |\d+?[+-]\d.?       -> [0-9] 1 or more times followed by either + or - followed by [0-9] 1 or more times
    |[+-]+?\.$          -> either + or - 1 or more times followed by . at the end of string
    |.+?[+-]$           -> any 1 or more times followed by either + or - at the end of string
    |.+?e+?.*?e+?       -> any 1 or more times followed by e 1 or more times followed by any zero or more times followed by e 1 or more times
    |\+[e+-]+?          -> + followed by either e or + or - 1 or more times
    |\-[e+-]+?          -> - followed by either e or + or - 1 or more times
    |\.[.+-]+?          -> . followed by either . or + or - 1 or more times
    |e\.+?              -> e followed by any 1 or more times
    )
    /gi;                -> flags: global and case insensitive

// Runtime: 76 ms, faster than 92.92% of JavaScript online submissions for Valid Number.
// Memory Usage: 37.5 MB, less than 12.50% of JavaScript online submissions for Valid Number.

Discussion

pic
Editor guide