Home > Software design >  Regex pattern to not to include zeros
Regex pattern to not to include zeros

Time:11-10

I need to match a pattern for validation . I want to match a decimal number where numeric part can have upto 14 digits including or - without 0 and after decimal has upto 4 digits. Valid patterns are :

 1.23
9857.6543
-745290.0

Invalid patterns are:

 0
 0.00
 1.23456

I have tried ^[0-9]{0,14}.[0-9]{0,4}$. I am not getting how to match for ,- and 0 condition

CodePudding user response:

Short answer: ^[ -]?[1-9][0-9]{0,13}\.[0-9]{1,4}$


^ - start of string

[ -]? optionally, one between and -

[1-9][0-9]{0,13} - a 14 digit number that doesn't start with 0

\. - decimal separator, has to be escaped or it will mean "any one character"

[0-9]{1,4} - up to 4 decimal digits

$ - end of string

CodePudding user response:

The pattern:

^[ -]?[^\D0]\d{0,13}\.\d{1,4}(?!\d)

matches the first 3 but not the second 3. [^\D0] is, if I'm not mistaken, strictly the same as [123456789], but slightly more compact.

CodePudding user response:

How about this?

^(?!0\.?0*$)[\ \-]?[0-9]{1,14}\.?[0-9]{0,4}$

Note: this does not match decimals without a leading 0 like .123 and does not match numbers with spaces in between the or -. Though, these could be added to the pattern.

Requiring a non-zero digit before a . eliminates fractions of whole numbers, like 0.123.

Also, if you don't want integers and only want decimals, you will need to modify to make the . required:

^(?!0\.?0*$)[\ \-]?[0-9]{1,14}\.[0-9]{0,4}$
  • Related