2

I'd like to extract all the occurences of this regex

\d{7,8}

(every number that has 7 or 8 length)

The input cuould be something like

asd123456789bbaasd

what I want is an array with:

["1234567", "12345678", "2345678", "23456789"]

all the possible occurencies of a number that has 7 or 8 lenth.

Regex.Matches works diferent, it returns all the consecutive occurencies of matches.... ["12345678"]

Any idea?

bobble bubble
  • 16,888
  • 3
  • 27
  • 46

2 Answers2

5

For overlapping matches you'd need to capture inside a lookahead.

(?=(\d{7}))(?=(\d{8})?)

See this demo at regex101

  • (?=(\d{7})) the first capturing group is mandatory and will capture any 7 digits
  • (?=(\d{8})?) the second capturing group is optional (triggered at same position)

So if there are 7 digit matches, they will be in group(1) and if 8 digit matches, in group (2). In .NET Regex you can probably use one name for both groups.

For getting 7 digit matches only if there are 8 ahead, drop the ? after (\d{8}) like in this demo.

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
2

Not really what you asked for, but the end result is.

using System;
using System.Collections.Generic;

namespace _52228638_ExtractAllPossibleMatches
{
    class Program
    {

        static void Main(string[] args)
        {
            string inputStr = "asd123456789bbaasd";
            foreach (string item in GetTheMatches(inputStr))
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }

        private static List<string> GetTheMatches(string inputStr)
        {
            List<string> retval = new List<string>();
            int[] lengths = new int[] { 7, 8 };
            for (int i = 0; i < lengths.Length; i++)
            {
                string tmp = new System.Text.RegularExpressions.Regex("(\\d{" + lengths[i] + ",})").Match(inputStr.ToString()).ToString();
                while (tmp.Length >= lengths[i])
                {
                    retval.Add(tmp.Substring(0, lengths[i]));
                    tmp = tmp.Remove(0, 1);
                }
            }
            return retval;
        }
    }
}
blaze_125
  • 2,262
  • 1
  • 9
  • 19