Home > OS >  Regex pattern matching for decimal
Regex pattern matching for decimal

Time:10-29

I need to match a pattern for validation . I want to match a decimal number where numeric part has upto 7 digits and after decimal has upto 9 numbers. Valid patterns are :

1.8
1234567.123456789
.8
0.7
12.78

I tried to use "^[0-9]{7}.[0-9]{9}$" but it is not working as expected

CodePudding user response:

The repetition argument specified in the curly brackets is for matching an exact number of matches of the previous token. Your regex is trying to match EXACTLY 7 digits ({7}), followed by EXACTLY 9 digits ({9}). You're also using the dot wildcard to match the decimal point, which you ought to be escaping with a slash (\.) as you intend to match the literal character dot rather than any character.

From the look of your examples, it seems you want to match between 0 and 7 digits before the decimal point, and then between 1 and 9 after. A suitable regex for this would be:

^[0-9]{0,7}\.[0-9]{1,9}$

Notice that I too am using repetition, but I am providing two arguments. The first argument is the minimum number of matches of the previous token, and the second argument is the maximum. This way we can be very explicit about the exact number of repetitions we expect.

  • Related