0

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

localhost
  • 822
  • 2
  • 20
  • 51

2 Answers2

3

You may use this regex with a lookahead to block 2 dots:

^(?!(?:\d*\.){2})[.\d]{1,18}$

RegEx Demo

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
  • $: End
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • wow this is amazing. I never knew there was `(` and `)`. what does it do? Can I add `[^-]` so it doesn't need negative value at all? – localhost May 04 '20 at 13:44
  • @Nofel There is no need for `[^-]` because `\d*\.?\d*` does not match `-`. `(?:...)` is a [non-capturing group](https://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group-in-regular-expressions), used to group or quantify sequences of patterns. `(?=...)` is a [positive lookahead](https://www.regular-expressions.info/lookaround.html) used to define context rather than match and consume characters. – Wiktor Stribiżew May 04 '20 at 13:46