Google Forms Regular Expressions (REGEX) comma delaminated (CSV)

Viewed 173

I have a Google form field, that contains 1 or more Id's

Patterns:

  • The IDs are always 6 numbers.
  • If only one ID is entered, a comma and a space is NOT required.
  • If more than one ID is entered, a comma and a space is required.
  • If more than one ID is entered, the last ID, should not have a comma or a space at the end.

Allowed Examples:

  • a single ID: 123456
  • multiple ID: 123456, 456789, 987654

Here is my current REGEX (does not work correctly)

[0-9]{6}[,\s]?([0-9]{6}[,\s])*[0-9]?

What am I doing wrong?

2 Answers

With your shown samples, could you please try following.

^((?:\d{6})(?:(?:,\s+\d{6}){1,})?)$

Online demo for above regex

Explanation: Adding detailed explanation of above regex.

^(                     ##Checking from starting of value, creating single capturing group.
   (?:\d{6})           ##Checking if there are 6 digits in a non-capturing group here.
   (?:                 ##Creating 1st non-capturing group here
      (?:,\s+\d{6})    ##In a non-capturing group checking it has comma space(1 or more occurrences) followed by 6 digits here.
   ){1,})?             ##Closing 1st non-capturing group here, it could have 1 or more occurrences of it.
)$                     ##Closing 1st capturing group here with $ to make sure its end of value.

You can use

^\d{6}(?:,\s\d{6})*$
  • ^ Start of string
  • \d{6} Match 6 digits
  • (?: Non capture group to repeat as a whole
    • ,\s\d{6} Match a , a whitespace char and 6 digits
  • )* Close group and optionally repeat
  • $ End of string

Regex demo

Related