Buscar..


Sintaxis

  • new Regex(pattern); // Crea una nueva instancia con un patrón definido.
  • Regex.Match(input); // Inicia la búsqueda y devuelve el Match.
  • Regex.Matches(input); // Inicia la búsqueda y devuelve una MatchCollection

Parámetros

Nombre Detalles
Modelo El patrón de string que se debe utilizar para la búsqueda. Para más información: msdn
RegexOptions [Opcional] Las opciones comunes aquí son Singleline y Multiline . Están cambiando el comportamiento de los elementos de patrón como el punto (.) Que no cubrirá una NewLine (\ n) en Multiline-Mode sino en el Multiline-Mode de Una SingleLine-Mode . Comportamiento por defecto: msdn
Tiempo de espera [Opcional] Donde los patrones son cada vez más complejos, la búsqueda puede consumir más tiempo. Este es el tiempo de espera superado para la búsqueda, tal como se conoce en la programación en red.

Observaciones

Necesitado usando

using System.Text.RegularExpressions;

Agradable tener

  • Puede probar sus patrones en línea sin la necesidad de compilar su solución para obtener resultados aquí: Haga clic en mí
  • Regex101 Ejemplo: Click me

Especialmente los principiantes tienden a exagerar sus tareas con expresiones regulares porque se siente poderoso y en el lugar correcto para búsquedas más complejas basadas en texto. Este es el punto en el que las personas intentan analizar documentos xml con expresiones regulares sin siquiera preguntarse si podría haber una clase ya terminada para esta tarea como XmlDocument .

Regex debería ser la última arma para elegir la complejidad. Al menos no olvide esforzarse para buscar el right way antes de escribir 20 líneas de patrones.

Partido individual

using System.Text.RegularExpressions;

string pattern = ":(.*?):";
string lookup = "--:text in here:--";

// Instanciate your regex object and pass a pattern to it
Regex rgxLookup = new Regex(pattern, RegexOptions.Singleline, TimeSpan.FromSeconds(1));
// Get the match from your regex-object
Match mLookup = rgxLookup.Match(lookup);

// The group-index 0 always covers the full pattern.
// Matches inside parentheses will be accessed through the index 1 and above.
string found = mLookup.Groups[1].Value;

Resultado:

found = "text in here"

Múltiples partidos

using System.Text.RegularExpressions;

List<string> found = new List<string>();
string pattern = ":(.*?):";
string lookup = "--:text in here:--:another one:-:third one:---!123:fourth:";

// Instanciate your regex object and pass a pattern to it
Regex rgxLookup = new Regex(pattern, RegexOptions.Singleline, TimeSpan.FromSeconds(1));
MatchCollection mLookup = rgxLookup.Matches(lookup);

foreach(Match match in mLookup)
{
    found.Add(match.Groups[1].Value);
}

Resultado:

found = new List<string>() { "text in here", "another one", "third one", "fourth" }


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow