Search code examples
javascriptregex

Writing Regex for handling optional floating point symbols at start of string?


I'm currently using a regex for detecting valid floating point numbers which looks like this:

/^[0-9]{1,10}(\.\d{0,3})?$/

I am able to match the following values as expect:

0
0.
0.1
0.12
0.123

I do however need to be able to validate and match the following inputs as these values can be parsed as a Number type in JavaScript.

.1
.12 
.123

I've looked at optional first character matching but so far I haven't been able to come up with a tangible solution. I think the fact that it's optional makes it tricky to implement


Solution

  • To match valid floating-point numbers, including those you provided (like .1, .12, .123), you can use the following regular expression:

    /^(?:\d{1,10}(\.\d{0,3})?|(\.\d{1,3}))$/
    

    EXPLANATION: your original regex correctly matches numbers with 1 to 10 digits before the decimal point and 0 to 3 digits after the decimal. However, it misses one key case: numbers that start with a decimal point (e.g., .1, .12, .123).

    To cover this missing case, I made two changes:

    1 - Made the digits before the decimal optional: I wrapped the part that matches digits before the decimal in a non-capturing group (?: ... )? and made it optional with ?. This allows the regex to match numbers that don’t have digits before the decimal, such as .1, .12, and .123.

    2 - Added an alternative to match numbers starting with a decimal: I added an alternative pattern (\.\d{1,3}) after a | (OR) operator to explicitly match cases where the number starts with a decimal point and has 1 to 3 digits after it. This ensures that numbers like .1, .12, and .123 are valid matches.