Home > Back-end >  Regex How to Match 2 fields
Regex How to Match 2 fields

Time:10-11

How would capture both the filenames inside the quotes, and the numbers following as named captures (Regex / C#)?

Files("fileone.txt", 5969784, "file2.txt", 45345333)

Out of every occurrence in the string, the ability to capture "fileone.txt" and the integer following (a loop cycles each pair)

I am trying to use this enter image description here

Reading match.Value to confirm what is being read. Only first pair is being picked up.

while (match.Success)
{
   MessageBox.Show(match.Value);
   match = match.NextMatch();
}

Now we are getting all results properly. I read, that Regex.Match only returns the first matched result. This explains a lot.

CodePudding user response:

You can use

(?:\G(?!\A)\s*,\s*|\w \()(?:""(?<file>.*?)""|'(?<file>.*?)')\s*,\s*(?<number>\d )

See the regex demo

Details:

  • (?:\G(?!\A)\s*,\s*|\w \() - end of the previous successful match and a comma enclosed with zero or more whitespaces, or a word and an opening ( char
  • (?:""(?<file>.*?)""|'(?<file>.*?)') - ", Group "file" capturing any zero or more chars other than a newline char as few as possible and then a ", or a ', Group "file" capturing any zero or more chars other than a newline char as few as possible and then a '
  • \s*,\s* - a comma enclosed with zero or more whitespaces
  • (?<number>\d ) - Group "number": one or more digits.

CodePudding user response:

I like doing it in smaller pieces :

            string input =  "cov('Age', ['5','7','9'])";
            string pattern1 = @"\((?'key'[^,] ),\s \[(?'values'[^\]] )";

            Match match = Regex.Match(input, pattern1);
            string key = match.Groups["key"].Value.Trim(new char[] {'\''});
            string pattern2 = @"'(?'value'[^'] )'";
            string values = match.Groups["values"].Value;
            MatchCollection matches = Regex.Matches(values, pattern2);
            int[] number = matches.Cast<Match>().Select(x => int.Parse(x.Value.Replace("'",string.Empty))).ToArray();
  • Related