Reputation: 861
I am trying the following Regex and It is failing
/^\d{1,18}[.]?$/
I want digit 1-18 but a optional dot(.) anywhere. I tried the following too
/^[1-9]{1,18}[.]?$/
It counts . as a character as well i.e 12345678901234567.
How can I achieve 18 digits and an optional . anywhere in regex
Upvotes: 0
Views: 37
Reputation: 785196
You may use this regex with a lookahead to block 2 dots:
^(?!(?:\d*\.){2})[.\d]{1,18}$
RegEx Details:
^
: Start(?!(?:\d*\.){2})
: Negative lookahead to disallow 2 dots[.\d]{1,18}
: Match dot or digit for length range between 1 to 18$
: EndUpvotes: 3
Reputation: 626896
You may use
^(?=(?:\.?\d){1,18}\.?$)\d*\.?\d*$
See the regex demo
Details
^
- start of string(?=(?:\.?\d){1,18}\.?$)
- a positive lookahead that requires 1 to 18 occurrences of an optional .
and any digit followed with an optional .
at the end of string\d*\.?\d*
- 0+ digits, an optional .
and again 0+ digits$
- end of string.Upvotes: 1