Califique este contenido
Contraer todo/Expandir todo Contraer todo
Esta página es específica de
Microsoft Visual Studio 2008/.NET Framework 3.5

Hay además otras versiones disponibles para:
Biblioteca de clases de .NET Framework
Regex (Clase)

Actualización: noviembre 2007

Representa una expresión regular inmutable.

Espacio de nombres:  System.Text.RegularExpressions
Ensamblado:  System (en System.dll)
Visual Basic (Declaración)
<SerializableAttribute> _
Public Class Regex _
    Implements ISerializable
Visual Basic (Uso)
Dim instance As Regex
C#
[SerializableAttribute]
public class Regex : ISerializable
Visual C++
[SerializableAttribute]
public ref class Regex : ISerializable
J#
/** @attribute SerializableAttribute */ 
public class Regex implements ISerializable
JScript
public class Regex implements ISerializable

La clase Regex contiene varios métodos static (o Shared en Visual Basic) que permiten utilizar una expresión regular sin crear explícitamente un objeto Regex. En la versión 2.0 de .NET Framework, las expresiones regulares compiladas a partir de llamadas a métodos estáticos se almacenan en la memoria caché, mientras que las expresiones regulares compiladas a partir de llamadas a métodos de instancia no se almacenan en la memoria caché. De forma predeterminada, el motor de expresiones regulares almacena en memoria caché las 15 últimas expresiones regulares estáticas usadas. Como resultado, en las aplicaciones que dependen en gran medida de un conjunto fijo de expresiones regulares para extraer, modificar o validar texto, quizás prefiera llamar a estos métodos estáticos en lugar de llamar a sus correspondientes métodos de instancia. Existen sobrecargas estáticas de los métodos IsMatch, Match, Matches, Replace y Split.

6f7hht7k.alert_note(es-es,VS.90).gifNota:

 Si el tamaño predeterminado de la memoria caché de 15 expresiones regulares estáticas es inadecuado para la aplicación, puede aumentarlo modificando el valor de la propiedad CacheSize.

En el ejemplo de código siguiente se ilustra el uso de una expresión regular para comprobar si una cadena tiene el formato correcto para representar un valor monetario. Observe el uso de los tokens ^ y $ que encierran la expresión para indicar que toda la cadena, no sólo una subcadena, debe cumplir la expresión regular.

Visual Basic
Imports System.Text.RegularExpressions

Public Module Test

   Public Sub Main()
      ' Define a regular expression for currency values.
      Dim rx As New Regex("^-?\d+(\.\d{2})?$")

      ' Define some test strings.
      Dim tests() As String = {"-42", "19.99", "0.001", "100 USD", _
                               ".34", "0.34", "1,052.21"}

      ' Check each test string against the regular expression.
      For Each test As String In tests
         If rx.IsMatch(test) Then
            Console.WriteLine("{0} is a currency value.", test)
         Else
            Console.WriteLine("{0} is not a currency value.", test)
         End If
      Next
   End Sub
End Module
' The example displays the following output to the console:
'      -42 is a currency value.
'      19.99 is a currency value.
'      0.001 is not a currency value.
'      100 USD is not a currency value.
'      .34 is not a currency value.
'      0.34 is a currency value.
'      1,052.21 is not a currency value.
C#
using System;
using System.Text.RegularExpressions;

public class Test
{
   public static void Main ()
   {
      // Define a regular expression for currency values.
         Regex rx = new Regex(@"^-?\d+(\.\d{2})?$");
          
         // Define some test strings.
         string[] tests = {"-42", "19.99", "0.001", "100 USD", 
                           ".34", "0.34", "1,052.21"};
          
         // Check each test string against the regular expression.
         foreach (string test in tests)
         {
            if (rx.IsMatch(test))
            {
               Console.WriteLine("{0} is a currency value.", test);
            }
            else
            {
               Console.WriteLine("{0} is not a currency value.", test);
            }
         }
   }    
}
// The example displays the following output to the console:
//       -42 is a currency value.
//       19.99 is a currency value.
//       0.001 is not a currency value.
//       100 USD is not a currency value.
//       .34 is not a currency value.
//       0.34 is a currency value.
//       1,052.21 is not a currency value.
Visual C++
#using <System.dll>

using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{

   // Define a regular expression for currency values.
   Regex^ rx = gcnew Regex( "^-?\\d+(\\.\\d{2})?$" );

   // Define some test strings.
   array<String^>^tests = {"-42","19.99","0.001","100 USD"};

   // Check each test string against the regular expression.
   System::Collections::IEnumerator^ myEnum = tests->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      String^ test = safe_cast<String^>(myEnum->Current);
      if ( rx->IsMatch( test ) )
      {
         Console::WriteLine( "{0} is a currency value.", test );
      }
      else
      {
         Console::WriteLine( "{0} is not a currency value.", test );
      }
   }
}

J#
import System.*;
import System.Text.RegularExpressions.*;

public class Test
{
    public static void main(String[] args)
    {
        // Define a regular expression for currency values.
        Regex rx = new Regex("^-?\\d+(\\.\\d{2})?$");

        // Define some test strings.
        String tests[] =  { "-42", "19.99", "0.001", "100 USD" };

        // Check each test string against the regular expression.
        for (int iCtr = 0; iCtr < tests.get_Length(); iCtr++) {
            String test = (String)tests.get_Item(iCtr);
            if (rx.IsMatch(test)) {
                Console.WriteLine("{0} is a currency value.", test);
            }
            else {
                Console.WriteLine("{0} is not a currency value.", test);
            }
        }
    } //main 
} //Test

En el ejemplo de código siguiente se ilustra el uso de una expresión regular para comprobar si aparecen palabras repetidas dentro de una cadena. Observe el uso de la construcción (?<word>) para nombrar un grupo y el uso de la construcción (\k<word>) para hacer referencia a ese grupo más adelante en la expresión.

Visual Basic
Imports System
Imports System.Text.RegularExpressions

Public Module Test

    Public Sub Main()
        ' Define a regular expression for repeated words.
        Dim rx As New Regex("\b(?<word>\w+)\s+(\k<word>)\b", _
               RegexOptions.Compiled Or RegexOptions.IgnoreCase)

        ' Define a test string.        
        Dim text As String = "The the quick brown fox  fox jumped over the lazy dog dog."

        ' Find matches.
        Dim matches As MatchCollection = rx.Matches(text)

        ' Report the number of matches found.
        Console.WriteLine("{0} matches found in:", matches.Count)
        Console.WriteLine("   {0}", text)

        ' Report on each match.
        For Each match As Match In matches
            Dim groups As GroupCollection = match.Groups
            Console.WriteLine("'{0}' repeated at positions {1} and {2}", _ 
                              groups.Item("word").Value, _
                              groups.Item(0).Index, _
                              groups.Item(1).Index)
        Next
    End Sub
End Module
' The example produces the following output to the console:
'       3 matches found in:
'          The the quick brown fox  fox jumped over the lazy dog dog.
'       'The' repeated at positions 0 and 4
'       'fox' repeated at positions 20 and 25
'       'dog' repeated at positions 50 and 54
C#
using System;
using System.Text.RegularExpressions;

public class Test
{

    public static void Main ()
    {

        // Define a regular expression for repeated words.
        Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
          RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Define a test string.        
        string text = "The the quick brown fox  fox jumped over the lazy dog dog.";

        // Find matches.
        MatchCollection matches = rx.Matches(text);

        // Report the number of matches found.
        Console.WriteLine("{0} matches found in:\n   {1}", 
                          matches.Count, 
                          text);

        // Report on each match.
        foreach (Match match in matches)
        {
            GroupCollection groups = match.Groups;
            Console.WriteLine("'{0}' repeated at positions {1} and {2}",  
                              groups["word"].Value, 
                              groups[0].Index, 
                              groups[1].Index);
        }

    }
    
}
// The example produces the following output to the console:
//       3 matches found in:
//          The the quick brown fox  fox jumped over the lazy dog dog.
//       'The' repeated at positions 0 and 4
//       'fox' repeated at positions 20 and 25
//       'dog' repeated at positions 50 and 54
Visual C++
#using <System.dll>

using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{
   // Define a regular expression for repeated words.
   Regex^ rx = gcnew Regex( "\\b(?<word>\\w+)\\s+(\\k<word>)\\b",static_cast<RegexOptions>(RegexOptions::Compiled | RegexOptions::IgnoreCase) );

   // Define a test string.        
   String^ text = "The the quick brown fox  fox jumped over the lazy dog dog.";

   // Find matches.
   MatchCollection^ matches = rx->Matches( text );

   // Report the number of matches found.
   Console::WriteLine( "{0} matches found.", matches->Count );

   // Report on each match.
   for each (Match^ match in matches)
   {
      String^ word = match->Groups["word"]->Value;
      int index = match->Index;
      Console::WriteLine("{0} repeated at position {1}", word, index);   
   }
}
J#
import System.*;
import System.Text.RegularExpressions.*;

public class Test
{
    public static void main(String[] args)
    {
        // Define a regular expression for repeated words.
        Regex rx = new Regex("\\b(?<word>\\w+)\\s+(\\k<word>)\\b", 
            RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Define a test string.        
        String text = "The the quick brown fox  fox jumped over the "
            + "lazy dog dog.";

        // Find matches.
        MatchCollection matches = rx.Matches(text);

        // Report the number of matches found.
        Console.WriteLine("{0} matches found.", (Int32)matches.get_Count());

        // Report on each match.
        for (int iCtr = 0; iCtr < matches.get_Count(); iCtr++) {
            Match match = matches.get_Item(iCtr);
            String word = match.get_Groups().get_Item("word").get_Value();
            int index = match.get_Index();
            Console.WriteLine("{0} repeated at position {1}", word, 
                (Int32)index);
        }
    } //main       
} //Test

La clase Regex es inmutable (de sólo lectura) y es inherentemente segura para la ejecución de subprocesos. Los objetos Regex pueden crearse en cualquier subproceso y los subprocesos pueden compartir dichos objetos. Para obtener más información, consulte Seguridad para subprocesos.

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC, Xbox 360

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

.NET Framework

Compatible con: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 3.5, 2.0, 1.0

XNA Framework

Compatible con: 2.0, 1.0
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2009 Microsoft Corporation. Reservados todos los derechos. Temas legales | Marcas Registradas | Declaración de privacidad
Page view tracker