Check string Regex C#

Asked

Viewed 172 times

6

I have a string that can only be composed by X capital and by -. Example : X-XX-XX or else X-X-X-XX-XXX. Where each - a group would be counted 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 also 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 also 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’ve tried that, 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 have tried several string Patterns and nothing, as I am locked in the group do not know what the procedure to count the digits of each group.

  • the data is always X or digits ?

  • The user can enter any sequence of X?

  • The 'X' is the mask that the individual will later use. Example the 'X-XX-XX' will become '1-01-01', '1-01-02'. But right now I want to count the amount of 'X' that was added to the mask.

  • Yes, can digital any sequence, 'XXXX-X' or 'XX-XXXX-X' the user you choose.

  • 1

    this could help you http://answall.com/questions/14619/como-separar-uma-string-de-acordo-com-um-separador-em-c

  • Yes, after making the split I could count the number of characters. I had not thought about the split. What would be the "correct", use the split, regex? You can do with Lilli too ?

  • I believe that as you want to count the amount of characters in each group between - just use split, and loop to count how many characters each group has

Show 3 more comments

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 working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.