The std/regex module wraps POSIX extended regular expressions. Three functions cover the most common operations: testing whether a pattern matches, extracting the first match, and replacing matches in a string. Patterns follow the standard POSIX ERE syntax.
// Expresiones regulares: regex_is_match, regex_match, regex_replace import "std/regex" // bool -> texto: int_to_string() espera un int y un bool no se convierte solo, // así que la conversión se escribe explícita. fn si_no(b: bool) -> String { if b { return "si" } return "no" } fn validar_email(email: String) -> bool { // Patrón POSIX básico para email return regex_is_match(email, "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9.-]+$") } fn main() -> int { // Validar emails let email1: String = "alice@example.com" let email2: String = "no-es-email" let email3: String = "bob.dev@nyx-lang.org" print("Email: " + email1 + " -> " + si_no(validar_email(email1))) print("Email: " + email2 + " -> " + si_no(validar_email(email2))) print("Email: " + email3 + " -> " + si_no(validar_email(email3))) // regex_match: retorna la primera coincidencia o "" let texto: String = "Nyx version 0.12.0 released" let resultado: String = regex_match(texto, "[0-9]+\\.[0-9]+\\.[0-9]+") print("Version encontrada: " + resultado) // regex_replace: reemplaza primera coincidencia let frase: String = "Hola mundo Nyx" let limpio: String = regex_replace(frase, " +", " ") print("Sin espacios dobles: " + limpio) // regex_replace_all: reemplaza todas las coincidencias let html: String = "<b>nyx</b> es <i>rapido</i>" let sin_tags: String = regex_replace_all(html, "<[^>]+>", "") print("Sin HTML: " + sin_tags) return 0 }
Email: alice@example.com -> si Email: no-es-email -> no Email: bob.dev@nyx-lang.org -> si Version encontrada: 0.12.0 Sin espacios dobles: Hola mundo Nyx Sin HTML: nyx es rapido
How it works
regex_is_match(str, pattern) returns a bool saying whether the pattern matches anywhere in the string; a bool does not go into int_to_string, so the recipe prints it through the si_no helper. Anchoring with ^ and $ forces a full-string match, which is essential for input validation like the email check here. Watch the character classes: a literal - inside brackets has to go first or last, otherwise POSIX reads it as a range and the whole class stops matching.
regex_match(str, pattern) returns the first substring that matches the pattern, or an empty string if there is no match. It is useful for extraction tasks such as parsing version numbers, dates, or identifiers out of larger text.
regex_replace substitutes only the FIRST match — which is why the output still shows the triple space before Nyx — while regex_replace_all replaces every non-overlapping match. The HTML tag-stripping example uses the pattern <[^>]+> to match any complete HTML tag and replaces it with an empty string, leaving only the text content.