1

Here is my pattern. I'm trying to allow numbers and a decimal with two places plus an optional comma with three digits.

var pattern = /^[0-9]+(,\d{3})*\.[0-9]{2}$/;

Allow

100,000.12

10,000.12

1,000.12

100.12

10.12

.12 (can't get this to allow... see below)

Don't allow

abcd

1,,000.12

1,00.12

1,000.0

1,000.

1,000

Here is the test. If I add a ? after [0-9] it works here, but it does not work in my MVC 5 View. The modal doesn't open, so MVC doesn't like it.

^[0-9]?+(,\d{3})*\.[0-9]{2}$

https://regex101.com/r/HwLS7q/1

UPDATE 1

Don't allow

000,000.12, 0.12 etc...

Any help is much appreciated! Thanks!

1 Answer 1

1

[0-9]?+ is a pattern that matches 1 or 0 digits possessively, not allowing backtracking into the pattern. JS regex does not support possessive quantifiers, hence the issue.

You need to use

^[0-9]*(?:,[0-9]{3})*\.[0-9]{2}$

Or

^(?:[0-9]+(?:,[0-9]{3})*)?\.[0-9]{2}$

Here, the [0-9]* match zero or more digits and (?:[0-9]+(?:,[0-9]{3})*)? matches an optional sequence of 1+ digits followed with 0+ repetitions of , and 3 digit groups.

See this regex demo.

A more precise pattern would be to restrict the first digit chunk to 1, 2 or 3 digits and make the integer part optional:

^(?:[0-9]{1,3}(?:,[0-9]{3})*)?\.[0-9]{2}$

See the regex demo.

Details

  • ^ - start of string
  • (?:[0-9]{1,3}(?:,[0-9]{3})*)? - an optional sequence of
    • [0-9]{1,3} - one to three digits
    • (?:,[0-9]{3})* - 0 or more repetitions of
      • , - comma
      • [0-9]{3} - three digits
  • \. - dot
  • [0-9]{2} - two digits
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

4 Comments

FYI, if you need to also match 100000.12, add \d+ alternative, ^(?:[0-9]{1,3}(?:,[0-9]{3})*|\d+)?\.[0-9]{2}$ (demo).
Thanks! I went with this one. ^(?:[0-9]{1,3}(?:,[0-9]{3})*)?\.[0-9]{2}$ Any idea how to not allow something like 000,000.12 or 000.12 or 00.12 or 0.12?
@Dumber_Texan2 ^(?:[1-9][0-9]{0,2}(?:,[0-9]{3})*)?\.[0-9]{2}$, see regex101.com/r/aTgmIu/6
Thanks for the help! The answer plus your explanations were spot-on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.