equiman
equiman

Reputation: 8132

RegEx Numeric with Length

How I can to create a Numeric Regex with decimal separator, but also limit the length

I create this:

^[0-9]([0-9]*[.]?[0-9]){1,10}$

Then 1234567890.1234567890 is valid, but is using 20(+1 -> decimal separator) characters.

How I can do to limit to 10 characters?

Valid:

1234567890
123456789.0
12345678.90
1234567.890
123456.7890
12345.67890
12345.67890
1234.567890
123.4567890
12.34567890
1.234567890

Not Valid:

12345678901
12345678901.
123456789.01
12345678.901
1234567.8901
123456.78901
12345.678901
12345.678901
1234.5678901
123.45678901
12.345678901
1.2345678901
.12345678901

Thanks in advance

Upvotes: 2

Views: 2268

Answers (2)

Bergi
Bergi

Reputation: 664297

It's more clear and maybe even faster if you don't use regex to count the length. Test it against ^\d+(?:\.\d+)$, remove dots and take the length.

If you really need it to be one regular expression, you can use lookahead to check the format and the length separately:

^\d{1,10}$|^(?=.{11}$)\d+\.\d+$

Explanation:

^          # At the start of the string
(?:        # either
 \d{1,10}  # up to 10 digits
|          # or
 (?=       # from here
  .{11}    # 11 characters
  $        # to the end
 )         # and as well
 \d+\.\d+  # two dot-separated digit sequences
)          # 
$          # 

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

^(?:\d{1,10}|(?!.{12})\d+\.\d+)$

Explanation:

^          # Start of string
(?:        # Either match...
 \d{1,10}  # an integer (up to 10 digits)
|          # or
 (?!.{12}) # (as long as the length is not 12 characters or more)
 \d+\.\d+  # a floating point number
)          # End of alternation
$          # End of string

Note that (as in your example) .123 or 123. are not valid.

Upvotes: 4

Related Questions