Expresiones Regulares (std::regex)
En esta página
std::regex ofrece las cuatro operaciones fundamentales sobre patrones: probar
presencia, encontrar todas las ocurrencias, sustituir y dividir. El módulo
acepta tanto sintaxis PCRE (\d, \s) como patrones Lua (%d, %s) —
consulta los comentarios inline de cada ejemplo para saber qué dialecto aplica.
Test
regex.test(patron, texto) retorna true si el patrón ocurre en algún punto
del texto. Usa ^ y $ para anclar al inicio y al fin:
Validación de email y filtrado de lista con filter + regex.test.
// Feature: regex.test — checks whether the string contains the pattern
// When to use: validate format (email, phone), filter a list by pattern.
use std::regex
use std::Array
// Matches any sequence of digits.
print(regex.test("\\d+", "abc123")) // expected: true
print(regex.test("\\d+", "abcdef")) // expected: false
// Anchored — entire string must be only digits.
print(regex.test("^\\d+$", "12345")) // expected: true
print(regex.test("^\\d+$", "12a45")) // expected: false
// Simplified email (without {n,} quantifier: we use `+`).
let email_re = "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]+$"
print(regex.test(email_re, "alice@example.com")) // expected: true
print(regex.test(email_re, "not an email")) // expected: false
// Filter emails out of a list.
let inputs = ["alice@a.com", "ops", "bob@b.io"]
let valid = inputs.filter(|e| regex.test(email_re, e))
print(valid.len()) // expected: 2
Find All
regex.find_all(patron, texto) devuelve un array de objetos con text,
start, stop y groups. regex.count es un atajo cuando solo importa
el número:
Extracción de números y palabras; nums[0].text accede a la subcadena.
// Feature: regex.find_all — every match of the pattern
// When to use: extract tokens (numbers, IDs, hashtags) from text.
use std::regex
// Each match is a table with `text`, `start`, `stop`, `groups`.
// NOTE: Zolo's regex module uses LUA patterns (`%d`, `%a`, ...),
// not PCRE syntax (`\d`).
let text = "I have 3 apples, 12 pears and 100 grapes"
let nums = regex.find_all("%d+", text)
print(nums.len()) // expected: 3
// The `text` field carries the exact substring.
print(nums[0].text) // expected: 3
print(nums[1].text) // expected: 12
print(nums[2].text) // expected: 100
// Extract words (alphanumeric tokens).
let words = regex.find_all("[a-z]+", "hello world zolo")
print(words.len()) // expected: 3
print(words[0].text) // expected: hello
print(words[2].text) // expected: zolo
// regex.count — shortcut that counts without collecting text.
print(regex.count("%d+", text)) // expected: 3
Replace All
regex.replace_all(patron, texto, sustituto) reemplaza todas las ocurrencias.
El sustituto puede referenciar grupos de captura con $1:
Enmascarar dígitos, normalizar espacios y cambiar etiquetas HTML por Markdown.
// Feature: regex.replace_all — replace every match
// When to use: anonymize data, strip noise, sanitize input.
use std::regex
// Mask every digit.
print(regex.replace_all("\\d", "id-12345", "*"))
// expected: id-*****
// Collapse multiple spaces into a single one.
print(regex.replace_all(" +", "a b c", " "))
// expected: a b c
// Strip a numeric prefix.
print(regex.replace_all("^\\d+ ?", "42 abc", ""))
// expected: abc
// Swap <b> tags for **.
print(regex.replace_all("<b>(.*?)</b>", "hello <b>world</b>!", "**$1**"))
// expected: hello **world**!
Split
regex.split(patron, texto) divide la cadena en todas las posiciones donde el
patrón coincide — útil para separadores variables o múltiples delimitadores:
División por espacios múltiples y por conjunto de delimitadores [,;|].
// Feature: regex.split — split a string by pattern
// When to use: split on multiple delimiters, varied whitespace.
use std::csv
use std::regex
// Split on any run of whitespace (1 or more).
let parts = regex.split("\\s+", "one two three four")
print(parts.len()) // expected: 4
print(parts[0]) // expected: one
print(parts[3]) // expected: four
// Split on comma, semicolon, or pipe.
let csv = regex.split("[,;|]", "a,b;c|d,e")
print(csv.len()) // expected: 5
print(csv[0]) // expected: a
print(csv[4]) // expected: e
// When the pattern does not match, returns the whole string in a single-element array.
let single = regex.split(",", "abc")
print(single.len()) // expected: 1
print(single[0]) // expected: abc
Desafío
Usa regex.find_all para extraer todas las direcciones de correo electrónico
de un texto libre y regex.replace_all para sustituirlas por [REDACTED].
Consulta también