¿Qué es la expresión regular en C#?

En C#, la expresión regular es un patrón que se usa para analizar y verificar si el texto de entrada dado coincide o no con el patrón dado. En C#, las expresiones regulares generalmente se denominan C# Regex. .Net Framework proporciona un motor de expresiones regulares que permite la coincidencia de patrones. Los patrones pueden consistir en cualquier literal de carácter, operadores o constructores. 
C# proporciona una clase denominada Regex que se puede encontrar en el espacio de nombres System.Text.RegularExpression . Esta clase realizará dos cosas:

  • Analizar el texto de entrada para el patrón de expresión regular.
  • Identificar el patrón de expresión regular en el texto dado.

Ejemplo 1: el siguiente ejemplo demuestra el uso de expresiones regulares en la verificación de números móviles. Supongamos que está creando un formulario en el que necesita verificar el número de teléfono móvil ingresado por el usuario, luego puede usar expresiones regulares. 

C#

// C# program to validate the Mobile
// Number using Regular Expressions
using System;
using System.Text.RegularExpressions;
 
class GFG {
     
    // Main Method
    static void Main(string[] args)
    {
        // Input strings to Match
        // valid mobile number
        string[] str = {"9925612824",
          "8238783138", "02812451830"};
         
        foreach(string s in str)
        {
            Console.WriteLine("{0} {1} a valid mobile number.", s,
                        isValidMobileNumber(s) ? "is" : "is not");
        }
         
        Console.ReadKey();
    }
     
    // method containing the regex
    public static bool isValidMobileNumber(string inputMobileNumber)
    {
        string strRegex = @"(^[0-9]{10}$)|(^\+[0-9]{2}\s+[0-9]
                {2}[0-9]{8}$)|(^[0-9]{3}-[0-9]{4}-[0-9]{4}$)";
         
        // Class Regex Represents an
        // immutable regular expression.
        //   Format                Pattern
        // xxxxxxxxxx           ^[0 - 9]{ 10}$
        // +xx xx xxxxxxxx     ^\+[0 - 9]{ 2}\s +[0 - 9]{ 2}\s +[0 - 9]{ 8}$
        // xxx - xxxx - xxxx   ^[0 - 9]{ 3} -[0 - 9]{ 4}-[0 - 9]{ 4}$
        Regex re = new Regex(strRegex);
         
        // The IsMatch method is used to validate
        // a string or to ensure that a string
        // conforms to a particular pattern.
        if (re.IsMatch(inputMobileNumber))
            return (true);
        else
            return (false);
    }
}

Producción:

9925612824 is a valid mobile number.
8238783138 is a valid mobile number.
02812451830 is not a valid mobile number.

Ejemplo 2: el siguiente ejemplo demuestra el uso de expresiones regulares en la verificación de ID de correo electrónico. Supongamos que está creando un formulario en el que necesita verificar la identificación de correo electrónico ingresada por el usuario, luego puede usar expresiones regulares.

C#

// C# program to validate the Email
// ID using Regular Expressions
using System;
using System.Text.RegularExpressions;
  
class GFG {
 
    // Main Method
    static void Main(string[] args)
    {
  
        // Input strings for Match
        // valid E-mail address.
        string[] str = {"parth@gmail.com",
                  "parthmaniyargmail.com",
                            "@gmail.com"};
         
        foreach(string s in str)
        {
            Console.WriteLine("{0} {1} a valid E-mail address.", s,
                                isValidEmail(s) ? "is" : "is not");
        }
         
    }
     
    // Method to check the Email ID
    public static bool isValidEmail(string inputEmail)
    {
         
        // This Pattern is use to verify the email
        string strRegex = @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z";
                           
        Regex re = new Regex(strRegex, RegexOptions.IgnoreCase);
         
        if (re.IsMatch(inputEmail))
            return (true);
        else
            return (false);
    }
}

Producción:

parth@gmail.com is a valid E-mail address.
parthmaniyargmail.com is not a valid E-mail address.
@gmail.com is not a valid E-mail address.

Sintaxis de expresiones regulares

Hay muchas sintaxis básicas como cuantificadores, caracteres especiales, clases de caracteres, agrupaciones y alternativas que se utilizan para las expresiones regulares.

Cuantificadores:

Subexpresión (Codicioso) Sub-expresión (Lazy) Partidos
* *? Se utiliza para hacer coincidir el carácter anterior cero o más veces.
+ +? Se utiliza para hacer coincidir el carácter anterior una o más veces.
? ?? Se utiliza para hacer coincidir el carácter anterior cero o una vez.
{norte} {norte}? Se utiliza para hacer coincidir el carácter anterior exactamente n veces.
{n,} {n,}? Se utiliza para hacer coincidir el carácter anterior al menos n veces.
{n, m} {n, m}? Se utiliza para hacer coincidir el carácter anterior de n a m veces.

Ejemplo 1:

C#

// C# program to demonstrate
// the * Quantifier
using System;
using System.Text.RegularExpressions;
 
class GFG {
     
    // Main Method
    public static void Main(string[] args)
    {
        // This will return any
        // pattern b, ab, aab, ...
        Regex regex = new Regex(@"a*b");
         
        Match match = regex.Match("aaaabcd");
        if (match.Success)
        {
            Console.WriteLine("Match Value: " + match.Value);
        }
    }
}

Producción:

Match Value: aaaab

Ejemplo 2:

C#

// C# program to demonstrate
// the + Quantifier
using System;
using System.Text.RegularExpressions;
  
class GFG {
     
    // Main Method
    public static void Main()
    {
         
        // this will return any pattern
        // like ab, aab, aaab, ....
        Regex regex = new Regex(@"a+b");
        Match match = regex.Match("aaabcd");
        if (match.Success)
        {
            Console.WriteLine("Match Value: " + match.Value);
        }
    }
}

Producción:

Match Value: aaab

Ejemplo 3:

C#

// C# program to demonstrate
// the ? Quantifier
using System;
using System.Text.RegularExpressions;
  
class GFG {
     
    // Main Method
    static void Main()
    {
         
         // This return any pattern like b, ab
        Regex regex = new Regex(@"a?b");
         
        Match match = regex.Match("aaaabcd");
         
        if (match.Success)
        {
            Console.WriteLine("Match Value: " + match.Value);
        }
    }
}

Producción:

Match Value: ab

Caracteres especiales

subexpresión Partidos
^ La palabra que sigue a este elemento coincide con el principio de la string o línea.
ps La palabra anterior a este elemento coincide al final de la línea o string.
.(Punto) Coincide con cualquier carácter solo una vez, excepto \n(nueva línea).
\d Se utiliza para hacer coincidir el carácter del dígito.
\D Se utiliza para hacer coincidir el carácter que no es un dígito.
\w Se utiliza para hacer coincidir cualquier carácter alfanumérico y de subrayado.
\W Se utiliza para hacer coincidir cualquier carácter que no sea una palabra.
\s Se utiliza para hacer coincidir los caracteres de espacio en blanco.
\S Se utiliza para hacer coincidir los caracteres que no son espacios en blanco.
\norte Se utiliza para hacer coincidir un carácter de nueva línea.

Ejemplo 1:

C#

// C# program to demonstrate
// the ^ Special Character
using System;
using System.Text.RegularExpressions;
  
class GFG {
     
    // Main Method
    static void Main()
    {
         
        // This will return if shyam exist
        // at the beginning of the line
        Regex regex = new Regex(@"^Shyam");
         
        Match match = regex.Match("Shyam is my pet name");
         
        if (match.Success)
        {
            Console.WriteLine("Match Value: " + match.Value);
        }
    }
}

Producción:

Match Value: Shyam

Ejemplo 2:

C#

// C# program to demonstrate
// the $ Special Character
using System;
using System.Text.RegularExpressions;
  
class GFG {
     
    // Main Method
    public static void Main()
    {
         
        // This return parth if it
        // exist at the end of the line
        Regex regex = new Regex(@"Parth$");
         
        Match match = regex.Match("My name is Parth");
         
        if (match.Success)
        {
            Console.WriteLine("Match Value: " + match.Value);
        }
    }
}

Producción:

Match Value: Parth

Ejemplo 3:

C#

// C# program to demonstrate
// the .(Dot) Special Character
using System;
using System.Text.RegularExpressions;
  
class GFG {
     
    // Main Method
    static void Main()
    {
         // This will return any word which
         // contains only one letter between
         // s and t
        Regex regex = new Regex(@"s..t");
         
        Match match = regex.Match("This is my seat");
         
        if (match.Success)
        {
            Console.WriteLine("Match Value: " + match.Value);
        }
    }
}

Producción:

Match Value: seat

Ejemplo 4:

C#

// C# program to demonstrate
// the \d Special Character
using System;
using System.Text.RegularExpressions;
  
class GFG {
     
    // Main Method
    static void Main()
    {
        // This will the return
        // the one digit character
        Regex regex = new Regex(@"\d");
         
        Match match = regex.Match("I am 19 years old");
         
        if (match.Success)
        {
            Console.WriteLine("Match Value: " + match.Value);
        }
         
    }
}

Producción: 

Match Value: 1

Clases de personajes

subexpresión Partidos
[] Se utiliza para hacer coincidir el rango de carácter
[Arizona] Se utiliza para hacer coincidir cualquier carácter en el rango de az.
[^az] Se utiliza para hacer coincidir cualquier carácter que no esté en el rango de az.
\ Se utiliza para hacer coincidir el carácter especial Escapado.

Ejemplo 1:

C#

// C# program to demonstrate
// the [] character class
using System;
using System.Text.RegularExpressions;
  
class GFG {
     
    // Main Method
    static void Main()
    {
         
        // This will return one character either
        // a or b or c which will come first
        Regex regex = new Regex(@"[abc]");
         
        Match match = regex.Match("abcdef");
         
        if (match.Success)
        {
            Console.WriteLine("Match Value: " + match.Value);
        }
    }
}

Producción:

Match Value: a

Ejemplo 2:

C#

// C# program to demonstrate
// the [a-z] character class
using System;
using System.Text.RegularExpressions;
  
class GFG {
     
    // Main Method
    static void Main()
    {
         
        // This will return any character
        // between x and z inclusive
        Regex regex = new Regex(@"[x-z]");
         
        Match match = regex.Match("xmax");
         
        if (match.Success)
        {
            Console.WriteLine("Match Value: " + match.Value);
        }
    }
}

Producción:

Match Value: x

Ejemplo 3:

C#

// C# program to demonstrate
// the [^a-z] character class
using System;
using System.Text.RegularExpressions;
  
class GFG {
     
    // Main Method
    static void Main()
    {
         
        // This will return other x,
        // y and z character
        Regex regex = new Regex(@"[^x-z]");
         
        Match match = regex.Match("xmax");
         
        if (match.Success)
        {
            Console.WriteLine("Match Value: " + match.Value);
        }
    }
}

Producción:

Match Value: m

Agrupación y Alternativas

subexpresión Partidos
() Se utiliza para la expresión de grupo.
(a|b) | El operador se utiliza para la alternativa a o b.
(?(exp) si|no) Si la expresión coincide, da sí; de lo contrario, da no.

Ejemplo 1:

C#

// C# program to demonstrate
// the grouping in regex
using System;
using System.Text.RegularExpressions;
  
class GFG {
     
    // Main Method
    static void Main()
    {
         
        // This will return pattern
        // will cd, cdcd, cdcdcd, ...
        Regex regex = new Regex(@"(cd)+");
         
        Match match = regex.Match("cdcdde");
         
        if (match.Success)
        {
            Console.WriteLine("Match Value: " + match.Value);
        }
    }
}

Producción:

Match Value: cdcd

Ejemplo 2:

C#

// C# program to demonstrate
// the grouping in regex
using System;
using System.Text.RegularExpressions;
  
class GFG {
     
    // Main Method
    static void Main()
    {
         
        // This will either d or e
        // which ever comes first
        Regex regex = new Regex(@"d|e");
         
        Match match = regex.Match("edge");
         
        if (match.Success)
        {
            Console.WriteLine("Match Value: " + match.Value);
        }
    }
}

Producción:

Match Value: e

Publicación traducida automáticamente

Artículo escrito por ParthManiyar y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Categories C#

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *