skip to Main Content

(?:[.,]?d{3})* this is a part of a monetary amount pattern which match the thousand separator and the 3 digits after. The thousand separator can either be ., , or nothing

But how to make it repetitive? If the first thousand separator is . then the rest should also be .

2

Answers


  1. You can use a capture group with a repeating backreference:

    ^(?:d{4,}|d{1,3}(?:([,.])d{3}(?:1d{3})*)?)$
    

    Explanation

    • ^ Start of string
    • (?: Non capture group for the alternatives
      • d{4,} Match 4 or more digits
      • | Or
      • d{1,3} Match 1-3 digits
      • (?: Non capture group
        • ([,.])d{3} capture either a . or comma in group 1
        • (?:1d{3})* Optionally repeat the backreference to group 1 (the same char) followed by 3 digits
      • )? Close the non capture group and make it optional (to also match 1-3 digits)
    • ) Close the non capture group
    • $ End of string

    See a regex demo.

    Login or Signup to reply.
  2. Take it block by block: the begining the middle and the end. Then use a or to match the numbers < 1000.

    ^((d{1,3}[.,]){,2}(d{3}[,.])*(d{3})|(d{1,3}))$

    (This works with python regex on this tool: https://regex101.com/)

    For PHP I had to modify it like this:

    ^(d{1,3}|(d{1,3}[.,])+(d{3}[.,])*d{3})$

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search