'Validate complex string input (fixed length pattern)

What is the best way to validate this type of input:

1234,4589,7889

Only allowed numbers. Each number must contain 4 digits. They are separated by ,. There can be one or many. Last item does not have a separator.



Solution 1:[1]

  • Each number must contain 4 digits : \d{4}
  • They are separated by "," : \d{4},\d{4}
  • There can be one or many : (?:\d{4},)+
  • Last item does not have a separator => aka 4 digits followed by any number of comma + 4 digits : \d{4}(?:,\d{4})*

^\d{4}(?:,\d{4})*$ to make sure the pattern cover the start and the end of the string.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joel