locked
Regex Match Pattern number range? RRS feed

  • Question

  • I'm trying to go threw a large string  and match a patterns like

    1,6,25,26,33,45,65  or  3,20,31,46,55,66,73  I got this close to work but it grabs extra charters

      string file = strd.ReadToEnd();
                    strd.Close();
                    strd.Dispose();

    string pattern = @",?\d+,\d+,\d+,\d+,\d+,\d+,\d+\s*";

    string Data2 = Regex.Replace(file, @"\s", "");
                    foreach (Match m in Regex.Matches(Data2, pattern, RegexOptions.Singleline))
                    {
                        string t = m.ToString();
                        if ("," != t.Substring(0, 1))
                        {
                            NewList.Add(t);

                        }

                    }

    I would rather use the range method [1-73], [1-73] ...etc , but I don't know how to set it up?

    Any Ideas... Thanks

    Friday, October 21, 2016 2:22 AM

Answers

  • @OP

    Forget all complications above, and see how much simpler, the method below is, when compared to the other.

    Just use this pattern:

            string patt=@"\b\d{1,2}\b";

    And then, build your List of integers, using this simple chain of methods:

            List<int> mylist=Regex.Matches(input,patt).OfType<Match>().Select(m=>int.Parse(m.Value)).ToList();

    where 'input' is a string type like:

            string input="1,34,65,22,7,9,11,18,57,32,66";

    • Proposed as answer by ritehere34Banned Monday, October 24, 2016 7:32 PM
    • Marked as answer by superlurker Monday, October 24, 2016 9:09 PM
    Monday, October 24, 2016 7:27 PM

All replies

  • In order to detect a sequence of seven numbers, try a combination of Regular Expressions and other techniques:

    string Data2 = ".... 1,6,25,26,33,45,65 ....";
    string pattern = @"((\d+)\s*,\s*){6}(\d+)";
    
    foreach( Match m in Regex.Matches( Data2, pattern, RegexOptions.Singleline ) )
    {
        var found = m.Groups[0].Value;
        string[] numbers = found.Split( ',' ).Select(n=>n.Trim()).ToArray();
    
        // add numbers to list. . .
    }
    

    If you want to only detect values between 1 and 73, then:

    string pattern = @"(?<!\d)((7[0-3]|[1-6][0-9]|[1-9])\s*,\s*){6}(7[0-3]|[1-6][0-9]|[1-9])(?!\d)";

    Friday, October 21, 2016 6:44 AM
  • I'm trying to learn this my self so can you break down:

    string pattern = @"((\d+)\s*,\s*){6}(\d+)... like what does {6} mean?

    string pattern = @"(?<!\d)((7[0-3]|[1-6][0-9]|[1-9])\s*,\s*){6}(7[0-3]|[1-6][0-9]|[1-9])(?!\d)

    ... like what does ((7[0-3]|[1-6][0-9]|[1-9])\s* mean?

    Thanks

    Friday, October 21, 2016 12:16 PM
  • Thanks
    Monday, October 24, 2016 9:09 PM