Duration of a wildcard expression

I am trying to create a regex with the following pattern. Number, maximum 16 digits, which may or may not have a comma inside, never at the beginning, never at the end. I've tried this:

^(?:\d+(?:,{1}\d+){1})$

      

The problem is that I cannot read the result of the group {0,16}. This is a list of numbers that must match the expression:

123.34
1.33333333
1222222233

Examples of numbers that shouldn't match:

1111,1111,1111
, 11111
11111,
111111111111111111111111111,111111111111111 (more than 16 characters)

+3


source to share


2 answers


If your regex flavor supports lookahead assertions, you can use this:

^(?!(?:\d{17,}$|[,\d]{18,}$))(?:\d+(?:,\d+)?)$

      

See here in Regexr



I removed the extra one {1}

and made a group with an optional share.

A negative statement (?!(?:\d{17,}$|[,\d]{18,}$))

verifies your length requirement. It fails if it finds 17 or more digits to the end OR 18 or more digits and commas to the end. That I am allowing multiple commas in the character class here is not a problem that only one comma is provided by the following pattern.

0


source


You can check the length before or with ^(?=[\d,]{1,16}$)(?:\d+(?:,\d+)?)$



It is an expression that checks the length before doing an actual match.

+1


source







All Articles