Aprende como crear expresiones regulares en 20 minutos

Si te encuentras frente a un problema y decides utilizar una expresión regular, tendrás dos problemas. O por lo menos eso es lo que dice el dicho entre los programadores. Las expresiones regulares son una poderosa herramienta que los programadores hábiles dejan como último recurso, pero cuando deciden usarlas, infunden el terror en los corazones de sus enemigos (y colegas).

Las expresiones regulares (o regex) son sentencias de un lenguaje especializado en la definición de reglas de coincidencia de patrones en un texto. Cuentan con sus propias reglas gramaticales y sintácticas, también llamadas pesadillas del novato. Si tienes problemas con este tipo de sentencias, aquí tienes todo lo que necesitas saber:

Encontrando un solo carácter

Cada lenguaje de programación tiene una manera de definir y utilizar las expresiones regulares. Cuentan con algunas diferencias, pero los conceptos básicos que se tratan en este artículo deben servir para cualquier entorno. Los ejemplos que utilizamos en este artículo están escritos en JavaScript, por lo que puedes probarlos en tu navegador.

Las expresiones regulares más básicas son aquellas que buscan un solo carácter. Estas son las reglas:

  • El punto (.) hace referencia a cualquier carácter. Si deseas buscar un punto como un caracter, escápalo de esta manera:
    .
  • Un signo de interrogación (?) indica que el carácter anterior es opcional. Si deseas buscar un signo de interrogación, escápalo de esta manera:
    ?

Aquí tienes un código de ejemplo de lo anteriormente explicado:

var text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit lest. Donec convallis dignissim ligula, et rutrum est elat vistibulum eu.';

// Will match both "elit" and "elat". The dot can match any character.
// Tip: try removing the "g" modifier of the regex to see what happens.

var regex = /el.t/g;

console.log( text.match(regex) );


// Will match both "est" and "lest". The question mark makes "l" optional.

var regex2 = /l?est/g;

console.log( text.match(regex2) );

Mostraría esto por pantalla:

["elit","elat"]
["lest","est"]

Buscando un carácter de un conjunto

Partiendo del ejemplo anterior, podemos escribir expresiones regulares que busquen cierto carácter mediante el uso de un set de caracteres:

  • Un set es uno o más caracteres encerrados entre corchetes [abc]. Busca solo uno de estos caracteres, en este ejemplo solamente a, b o c. Puedes negar un set con ^. [^abc] buscará cualquier carácter que no sea a, b o c. También puede especificar un rango [0-9], [az], que coincidirá con toda la gama.
  • Hay sets integrados que hacen que sea más fácil escribir expresiones regulares (se les llama shorthand). En lugar de [0-9], puedes escribir
    d
    y para [^0-9], puedes escribir
    D
    . También los hay para caracteres de letras. Por ejemplo, para referirnos a cualquier carácter de la A a la Z, incluyendo dígitos y guiones bajos, podemos escribir
    w
    o
    W
    , y para espacios, saltos de línea y tabulaciones, podemos escribir
    s
    o
    S

Este ejemplo hace las cosas más claras:

// Match only "cat" and "can", but not "car".

var text = 'cat car can';

console.log( text.match(/ca[tn]/g) );

// Match everything BUT cat and can (notice the ^ symbol)

console.log( text.match(/ca[^tn]/g) );


// Here is another example, which matches only the number

text = 'I would like 8 cups of coffee, please.';


console.log('How many cups: ' + text.match( /[0-9]/g ));

// A better, shorter way to write it, using the d character class

console.log('How many cups: ' + text.match( /d/g ));


// Matching everything BUT the number (will return an array of chars)

console.log( text.match(/D/g) );

Mostraría esto por pantalla:

["cat","can"]
["car"]
How many cups: 8
How many cups: 8

Buscando palabras

La mayoría de las veces, tendrás que encontrar palabras enteras, en vez de caracteres individuales. Esto se hace mediante el uso de modificadores que indican repeticion en un caracter o en un conjunto de caracteres. Estos son:

  • +, Que se repite el carácter anterior una o más veces
  • *, Que repite el carácter anterior cero o más veces
  • {X} durante un número exacto de repeticiones, {x, y} para un número variable de repeticiones (donde x e y son números)

Además, el patrón especial

b

busca en los extremos de las palabras (no es un símbolo real).

var text = 'Hello people of 1974. I come from the future. In 2014 we have laser guns, hover boards and live on the moon!';

// Find the years. d+ will match one or more chars

var yearRegex = /d+/g;

console.log('Years: ', text.match( yearRegex ) );


// Find all sentences. Our sentences begin with a capital letter and end in either a dot or an exclamation mark.
// The question mark makes the regex non-greedy. Try removing it.

var sentenceRegex = /[A-Z].+?(.|!)/g;

console.log('Sentences: ', text.match(sentenceRegex) );


// Find all words that begin with h. We want to match both lower and upper case, so we include the i modifier.
// Notice the b for word boundary. Try removing it.

var hWords = /bhw+/ig;

console.log('H Words: ', text.match(hWords) );


// Find all words between four and six characters

var findWords = /bw{4,6}b/g;

console.log( 'Words between 4 and 6 chars: ', text.match(findWords) );


// Find words longer than 5 chars

console.log( 'Words 5 chars or longer: ', text.match(/bw{5,}b/g) );


// Find words exactly 6 chars long

console.log( 'Words exactly 6 chars long: ', text.match(/bw{6}b/g) );

Mostraría esto por pantalla:

Years: ["1974","2014"]
Sentences: ["Hello people of 1974.","I come from the future.","In 2014 we have laser guns, hover boards and live on the moon!"]
H Words: ["Hello","have","hover"]
Words between 4 and 6 chars: ["Hello","people","1974","come","from","future","2014","have","laser","guns","hover","boards","live","moon"]
Words 5 chars or longer: ["Hello","people","future","laser","hover","boards"]
Words exactly 6 chars long: ["people","future","boards"]

Validando líneas enteras

En JavaScript, este es el tipo de patrones que utilizaríamos para validar campos de texto introducidos por el usuario. Es sólo una expresión regular ordinaria, pero anclada al inicio y al final del texto usando las expresiones ^ (inicio de la línea), $ (fin de línea). Con esto nos aseguraremos de que el patrón escrito comprende toda la longitud del texto, y no sólo con una parte de él.

También, en este caso utilizamos el método test() del objeto regex, que devuelve true o false si la expresión regular coincide con la cadena.

// We have an array with strings. Let's extract only the URLs!

var strings = [
	'http://programacion.net/articulos/',
	'this is not a URL',
	'https://google.com/',
	'123461',
	'http://programacion.net/?search=jquery',
	'http://not a valid url',
	'abc http://invalid.url/'
];

// Here is a simple regex that will do the job. Note the ^ and $ symbols for beggining and end of line. 
// Try removing them and see which URLs are detected.

var regex = /^https?://[w/?.&-=]+$/;

var urls = [];

for( var i = 0; i < strings.length; i++ ){

	if( regex.test(strings[i]) ){
		
		// This is a valid URL
		urls.push(strings[i]);

	}

}

console.log('Valid URLs: ', urls);

Mostraría esto por pantalla:

Valid URLs: ["http://programacion.net/articulos/","https://google.com/","http://programacion.net/?search=jquery"]

Fuente: tutorialzine.com

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP