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

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.

Read more here: Source link