Check string Regex C #

6

I have a string that can only be composed of X uppercase and - . Example: X-XX-XX or X-X-X-XX-XXX . Where every - would count one group and each X one digit.

Example 1: The string X-XX-XX has 3 groups, the first group contains 1 digit, the second contains 2 digits, and the third contains 2 digits.

Example 2: The string X-X-X-XX-XXX has 5 groups, the first group contains 1 digit, the second contains 1 digit and the third contains 1 digit, the fourth contains 2 digits and the fifth contains 3 digits.

How do I get the information as described in Example 1 and 2.

I have tried this, to count the number of groups:

    public static int ValidaMascaraPlanoDeContas(string Mascara)
    {
        var regex = new Regex(@"([X])\w+/g");
        var match = regex.Match(Mascara);

        return match.Groups.Count;

    }

I've tried several string patterns and nothing, as I'm stuck in the group I do not know the procedure for counting the digits of each group.

    
asked by anonymous 20.12.2016 / 19:57

1 answer

5

I would use C # itself to do this with the Split method;

using System;

public class Program
{
    public static void Main()
    {
        string teste = "X-X-X-XX-XXX";

        string[] grupos = teste.Split('-');

        Console.WriteLine(grupos.Length);

        foreach(var grupo in grupos)
        {
            Console.WriteLine(grupo.Length);
        }
    }
}

See it working .

    
20.12.2016 / 20:13