Home > Enterprise >  Validate list of single digits in a list of comma separated values. Regex
Validate list of single digits in a list of comma separated values. Regex

Time:08-11

Hope you can help me, this thing is driving me crazy. I'm trying to validate user input, which is a list of comma separated numbers.Only the lists of values which contain at least one of the following single digits should pass: 1, 2, 3. For example, the following list of values are valid:

  • 1,6,9,7
  • 3
  • 65,2
  • 46,57,1,6

Whereas the following is not:

  • 222,111,33

  • 9,8,7

  • 4,5,6

  • 111

CodePudding user response:

/\b[123]\b/g a single class of 1, 2, or 3 surrounded by word boundaries. Word boundaries (\b) are matched by a word and then matched by a non-word:

 \b⇩ ⇩\b
   1,

Regex101

CodePudding user response:

^(?:\d ,)*[123](?:,\d )*$

Basically how the above works are is it captures any valid sequence before and after a valid number and if there are no fails it is successful.

 ^             'start
(?:\d ,)*      'match as many as we want before  ie. 44,33,44,55,
[123]          'match our number
(?:,\d )*      'match as many as we want after   ie ,0,2,5
$              'should be the end of the string

https://regex101.com/r/rgB2AM/2

  • Related