Search code examples
regexnumericregex-lookaroundsregex-group

Regex expression help to allow complete digits or with 3 special characters followed by 4 digits in comma separated without spaces


Looking for some help on regex expression for below use case.

My input field should allow only comma separated values of either just digits, or a sequence of special characters (*) followed by digits. It should able to allow below combinations:

1234,***1234,3456
***1234,***3456,12345567
1234,3456
***1234,***3456

The digits only case can have max 10 digits. The case with special characters and digits should have 3 asterisks followed by 4 digits.


Solution

  • This validates a string of comma separated items, where each item is either a number of up to 10 digits, or three * followed by a 4 digit number:

    /^(?:\d{1,10}|\*{3}\d{4})(?:,(?:\d{1,10}|\*{3}\d{4}))*$/
    

    Explanation:

    • ^ - anchor at start of string
    • (?: - non capture group start
      • \d{1,10} - 1 to 10 digits
      • | - logical OR
      • \*{3}\d{4} - three * followed by 4 digits
    • ) - non capture group end
    • (?: - non capture group start
      • ,(?:\d{1,10}|\*{3}\d{4}) - a comma, followed by same ORed pattern as above
    • )* - non capture group end, whole group has zero to many repetitions
    • $ - anchor at end of string