0

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".

Vishnu CS
  • 748
  • 1
  • 10
  • 24
Tisha
  • 61
  • 1
  • 2
  • 11
  • What does "accepting an array of 7 such elements" mean to you? – Enigmativity Sep 09 '20 at 05:07
  • If you just want to parse and get a `string[]` then you should use `Newtonsoft.Json` and just do this: `string[] output = (JsonConvert.DeserializeObject(source) as JArray).Select(t => t.Value()).ToArray();`. – Enigmativity Sep 09 '20 at 05:13
  • Seriously, what does "a single line regex pattern as a part of creating a json template which would accept the pattern of the 'array of strings'" mean? – Enigmativity Sep 09 '20 at 05:48

1 Answers1

0

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.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • I read the question as the OP has `string source = @"[""9H"", ""0000"", ""0000"", ""10123"", ""7809"", ""0000"", ""0000""]";` and they want to parse it to a `string[]`. – Enigmativity Sep 09 '20 at 05:21
  • This is done as a part of creating a JSON Template. I am looking for a single line pattern which would accept this array of strings. eg, if the array was ["0000"], my pattern would be "^[0-9]{4}$" – Tisha Sep 09 '20 at 05:25
  • @lakshmisubhash - Can you please define what "accept this array of strings" means? Can you please show, as valid C# code, what the input data is that you're working with, and then what you expect the output to be? – Enigmativity Sep 09 '20 at 05:50
  • I am not writing a piece of C# code. Let me explain what I am doing - i have to specify a pattern for a template. Later when i give inputs to this template, i checks if the pattern of input given matches with the pattern specified in template. If yes, it accepts the input and we process it. E.g, if the template should accept only integers, I would specify the pattern as "^[0-9]$". Here, i am looking for such a single line pattern which would accept this array of strings. – Tisha Sep 09 '20 at 13:55