Nyx by Example

Regular Expressions

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.

Code

// Expresiones regulares: regex_is_match, regex_match, regex_replace

import "std/regex"

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 + " -> " + int_to_string(validar_email(email1)))
    print("Email: " + email2 + " -> " + int_to_string(validar_email(email2)))
    print("Email: " + email3 + " -> " + int_to_string(validar_email(email3)))

    // regex_match: retorna la primera coincidencia o ""
    let texto: String = "Nyx version 0.12.0 released"
    let match: String = regex_match(texto, "[0-9]+\\.[0-9]+\\.[0-9]+")
    print("Version encontrada: " + match)

    // 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 = "nyx es rapido"
    let sin_tags: String = regex_replace_all(html, "<[^>]+>", "")
    print("Sin HTML: " + sin_tags)

    return 0
}

Output

Email: alice@example.com -> 1
Email: no-es-email -> 0
Email: bob.dev@nyx-lang.org -> 1
Version encontrada: 0.12.0
Sin espacios dobles: Hola mundo Nyx
Sin HTML: nyx es rapido

Explanation

regex_is_match(str, pattern) returns a bool (represented as 1/0 when printed via int_to_string) indicating whether the pattern matches anywhere in the string. Anchoring with ^ and $ forces a full-string match, which is essential for input validation like the email check here.

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 the first match with a replacement string, 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.

← Previous Next →

Source: examples/by-example/17-regex.nx