Búsqueda y Prueba
En esta página
Tres métodos cubren la mayoría de las verificaciones de formato y filtrado sin necesitar expresiones regulares:
.contains(sub)— ¿existe la substring en cualquier posición?.starts_with(prefijo)— ¿comienza con ese texto?.ends_with(sufijo)— ¿termina con ese texto?
Todos son case-sensitive: normaliza con .lower() antes si necesitas una
comparación sin distinción de mayúsculas.
Verificación de prefijo, sufijo y substring; validación de URL y extensión de archivo.
06-search-and-test.zolo
// Feature: Searching and testing strings
// Syntax: `.contains(sub)`, `.starts_with(p)`, `.ends_with(s)`
// When to use: validate format, filter, decide without regex.
use std::regex
use std::url
let phrase = "the quick brown fox"
// -- contains: does the substring exist? ------------------------
print(phrase.contains("quick"))
// expected: true
print(phrase.contains("cat"))
// expected: false
// -- starts_with / ends_with -----------------------------------
print(phrase.starts_with("the"))
// expected: true
print(phrase.ends_with("fox"))
// expected: true
print(phrase.starts_with("THE"))
// expected: false (case-sensitive)
// -- Practical cases -------------------------------------------
// Validate URL prefix.
fn is_https(url: str) -> bool {
return url.starts_with("https://")
}
print(is_https("https://zolo-lang.devzolo.com")) // true
print(is_https("http://example.com")) // false
// Validate file extension.
fn is_image(name: str) -> bool {
return name.ends_with(".png") || name.ends_with(".jpg")
}
print(is_image("photo.png")) // true
print(is_image("doc.pdf")) // false
// Filter list by substring.
let files = ["main.zolo", "test.rs", "lib.zolo", "build.sh"]
for f in files {
if f.contains(".zolo") {
print(f)
}
}
// expected:
// main.zolo
// lib.zolo
Desafío
Escribe una función is_zolo_file(name: str) -> bool que devuelva true solo
si el nombre termina con .zolo y no empieza con _. Pruébala con "main.zolo",
"_test.zolo" y "lib.rs".
Consulta también