-1

I'm a network engineer working with multiple version of Cisco's IOS and need to use multiple regular expression patterns. Is there a way to build an array of regex patterns?

I've used regex patterns in various other programs, but when I started building this I have 3 pattern formats to search for so far and will be adding more as I go through our network, no doubt.

I've tried the usual:

Regex someVariable[] = new Regex();

This is currently what I have and would like to clean this up into an array for future loop searches through the patterns or so I can just call them individually as needed someVariable[0], etc.

Regex intRegex = new Regex(@"((?<!\S)[A-Za-z]{2}\d{1,5}\S+\s+)|(\s[A-Za-z]{7,15}\d{1,5}\S+\s+)", RegexOptions.Compiled);
        Regex psRegex = new Regex(@", id\s+\d{10},", RegexOptions.Compiled);
        Regex cidRegex = new Regex(@"\d{3}-\d{3}-\d{4}", RegexOptions.Compiled);
        Regex vcidRegex = new Regex(@"vcid\s\d{10},", RegexOptions.Compiled);

I'm not sure what my options are with c# as I've never walked down this path with c# before and in the past have only ever used 1 or maybe 2 Regex search patterns in an entire program before.

  • 1
    Not sure what the issue is. Define a `List`, then `.Add` as many regexps as you need. Then, iterate over them when looking for matches. – Wiktor Stribiżew Aug 21 '19 at 09:28
  • If you make a LIst> and make the key the variable name and the value the regex pattern you can enumerate through the list. – jdweng Aug 21 '19 at 09:28
  • Maybe you can try to use ```Dictionary```,add like ```dic.Add(key,regex)```,you can get regex by key like ```dic[key]```. – melody zhou Aug 21 '19 at 09:35

1 Answers1

1

Try this

    Regex[] regexCollection = new Regex[4];

    Regex intRegex = new Regex(@"((?<!\S)[A-Za-z]{2}\d{1,5}\S+\s+)|(\s[A-Za-z]{7,15}\d{1,5}\S+\s+)", RegexOptions.Compiled);
    Regex psRegex = new Regex(@", id\s+\d{10},", RegexOptions.Compiled);
    Regex cidRegex = new Regex(@"\d{3}-\d{3}-\d{4}", RegexOptions.Compiled);
    Regex vcidRegex = new Regex(@"vcid\s\d{10},", RegexOptions.Compiled);

    regexCollection[0] = intRegex;
    regexCollection[1] = psRegex;
    regexCollection[2] = intRegex;
    regexCollection[3] = vcidRegex;
Sheraz Ahmed
  • 405
  • 1
  • 4
  • 20