Expression Régulière: Exemple d’utilisation de groupe

Author:


{filelink=18792}

using System;
using System.Text.RegularExpressions;

public class ExempleGroupe
{

  public static void Main()
  {

    // Créer un String qui contient les numéros de téléphones et leurs indicatifs
    string text =
      "(800) 55-25-12-11" +
      "(212) 55-85-12-12" +
      "(506) 55-95-12-13" +
      "(650) 55-65-12-14" +
      "(888) 55-25-12-15";

    // Créer une expression régulière qui correspond
    // à l'indicatif des numéros des téléphones
    // Nous allons nommer ce groupe "groupeIndicatif"
    string groupeIndicatifRegExp = "(?(ddd))";

    // Créer une expression régulière qui correspond
    // auxs numéros des téléphones
    // Nous allons nommer ce groupe "groupeTelephone"
    // Il est constitué de 8 chiffre séparer par trait d'union
    string groupPhoneRegExp = "(?dd-dd-dd-dd)";

    // Créer un objet 'MatchCollection' pour stocker les valeurs qui correspnds à l'expression
    MatchCollection monMatchCollection =
      Regex.Matches(text, groupeIndicatifRegExp + " " + groupPhoneRegExp);

    // Parcourir le MatchCollection avec forEach
    foreach (Match match in monMatchCollection)
    {

        Console.WriteLine("Indicatif = " + match.Groups["groupeIndicatif"]);

        Console.WriteLine("Téléphone = " + match.Groups["groupeTelephone"]);

      foreach (Group group in match.Groups)
      {

        foreach (Capture capture in group.Captures)
        {
          Console.WriteLine("Valeur de Capture = " + capture.Value);
        }

      }

    }

  }

}

Leave a Reply

Your email address will not be published. Required fields are marked *