Regex for array of strings

11.5k Views Asked by At

I am new to this area and am trying to write a single line regex pattern as a part of creating a json template which would accept the pattern of the 'array of strings':

["9H", "0000", "0000", "10123", "7809", "0000", "0000"]

Till now, I have found the regex for individual elements, say "^[0-9][A-Z]$" for first element, "^[0-9]{4}$" for second element and so on.

But I need to specify a pattern of string accepting an array of 7 such elements, without any change in the number of integers/char in each element. (i.e, "10123" can be "12345" but should not be "123456".

1

There are 1 best solutions below

4
On

Regular expressions work on strings, so this means you have two options:

  1. Convert your entire array into one big string (with for example arr.join('|')) so you can write 1 large regular expression to test it.
  2. Don't do this. Just manually write out the code for the first element, and loop through the rest of the elements and use the appropriate regular expression for each part.

#2 makes a lot more sense to me. Might be a bit more code, but that code will be more legible.