[C#] Collecting part of output stream and putting it into a list

Discussion in 'Mixed Languages' started by CODYQX4, Dec 10, 2010.

  1. CODYQX4

    CODYQX4 MDL Developer

    Sep 4, 2009
    4,813
    45,775
    150
    #1 CODYQX4, Dec 10, 2010
    Last edited: Apr 15, 2019
    .
     
  2. Calistoga

    Calistoga MDL Senior Member

    Jul 25, 2009
    421
    199
    10
    #2 Calistoga, Dec 10, 2010
    Last edited by a moderator: Apr 20, 2017
    Does this work? I wrote the code directly into this post, so I may have made errors ;)

    Code:
    string pattern = @"(?<Number>\d+?)\.\s+?(?<License>(?:\d|\w){8}-(?:(?:\d|\w){4}-){3}(?:\d|\w){12})";
    
    Regex regex = new Regex(pattern);
    
    MatchCollection matches = regex.Matches(yourStringWithData);
    
    // This can be changed to <int, string> if you want to convert the number into an integer type with int.Parse() or int.TryParse().
    Dictionary<string, string> licenses = new Dictionary<string, string>();
    
    foreach (Match match in matches)
    {
        string number = match.Groups["Number"].Value;
        string license = match.Groups["License"].Value;
    
        // Use the matched strings
        licenses.Add(number, license);
    }
    
    // All licenses can now be accessed from the dictionary
    
     
  3. CODYQX4

    CODYQX4 MDL Developer

    Sep 4, 2009
    4,813
    45,775
    150
    #3 CODYQX4, Dec 10, 2010
    Last edited: Apr 15, 2019
    (OP)
    .
     
  4. Calistoga

    Calistoga MDL Senior Member

    Jul 25, 2009
    421
    199
    10
    #4 Calistoga, Dec 11, 2010
    Last edited by a moderator: Apr 20, 2017
    Glad you got it working :) This is a revised version that disregards the 0.'s - just posting it for future reference

    Code:
    using System.Collections.Generic;
    using System.Text.RegularExpressions;
    
    string pattern = @"(?:\d|\w){8}-(?:(?:\d|\w){4}-){3}(?:\d|\w){12}";
    
    Regex regex = new Regex(pattern);
    
    MatchCollection matches = regex.Matches(yourStringWithData);
    
    List<string> licenses = new List<string>();
    
    foreach (Match match in matches)
    {
        string license = match.Value.ToLowerInvariant().Trim(); // For casing consistency, and removes eventual spaces
    
        licenses.Add(license);
    }