3

I am using the following regex in my app:

^(([0-9|(\\,)]{0,10})?)?(\\.[0-9]{0,2})?$

So it allows 10 characters before the decimal and 2 character after it. But I am inserting one additional functionality of formatting textfield as currency while typing. So if I have 1234567 it becomes 1,234,567 after formatting. The regex fails when I enter 10 characters instead of 10 digits. Ideally it should be that regex ignores the commas when counting 10.

I tried this too ^(([0-9|(\\,)]{0,13})?)?(\\.[0-9]{0,2})?$ but it doesn't seem the right approach. Can anyone help me get a proper regex instead of using this tweak.

Mamta
  • 921
  • 1
  • 10
  • 28

1 Answers1

2

You may use

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

Or, if there must be a digit after . in the fractional part use

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

See the regex demo. The (?:,*[0-9]){0,10} part is what does the job: it matches any 0+ , chars followed with a single digit 0 to 10 times. If , can also appear before ., add ,* after the ((?:,*[0-9]){0,10})?.

Details

  • ^ - start of string
  • (?:,*[0-9]){0,10} - 0 to 10 occurrences of 0+ commas followed with a digit
  • (?:\.[0-9]{0,2})? - an optional sequence of:
    • \. - a period
    • [0-9]{0,2} - 0 to 2 digits (if there must be a digit after . use [0-9]{1,2})
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563