For today's problem, we were required to write a number validation function. This is a typical regex problem. A regex according to Wikipedia is a regular expression (shortened as regex or regexp) and is a sequence of characters that specifies a search pattern in text.
The bulk of the problem lies within writing the right regex pattern. In most cases, regex patterns are language agonistic. Because of these characteristics of regex I was able to use the same regex pattern to write the number validation function in python and javascript, which the python program turned out to be more efficient both in time and space complexities. Let's take a look at the problem statement.
Problem Statement:
Click here to read the problem statement on leetcode
My Approach:
The important questions to ask while writing a regex pattern is :
1) what are the various sub-groups of this regex 2) what sub-groups are optional 3) what is the acceptable range for each sub-group or character class 4) how does the regex begin and how does it end
when you answer these questions you would see that
1) a valid number has three sub-groups i) the sign ii) the number iii) the exponent 2) the sign sub-group and the exponent sub-groups are optional parts of a valid number 3) the e or E part of the exponent subgroup needs to be asserted to appear only once in the pattern that is if its sub-group is present, the same applies to the sign sub-group 4) a valid number must start with either a sign, a number, or a decimal point and must end with a number
when all these a put into consideration, you would come up with the right regex pattern below
^(([-+])?((\d+\.?\d*)|(\d*\.?\d+)))(([eE]){1}([-+])?(\d+))?$
Then the following Python or javascript code is used to implement the number validator function
Python
class Solution:
def isNumber(self, s: str) -> bool:
regex = re.compile('^(([-+])?((\\d+\\.?\\d*)|(\\d*\\.?\\d+)))(([eE]){1}([-+])?(\\d+))?$')
return regex.match(s)
JavaScript
/**
* @param {string} s
* @return {boolean}
*/
var isNumber = function(s) {
const regex = new RegExp('^(([-+])?((\\d+\\.?\\d*)|(\\d*\\.?\\d+)))(([eE]){1}([-+])?(\\d+))?$')
return regex.test(s)
};
what the code is doing is basically running the match method on the regex object. This method takes a string argument and returns true if it matches the regex pattern Similarly, for js, the test method is called on the regex object taking a string as an argument and returning true if the string matches the pattern