Saltar al contenido principal

🔍 Expresiones Regulares

📖 ¿Qué son las Expresiones Regulares?

Las expresiones regulares (Regular Expression, Regex) son una forma de expresar patrones de cadenas. Se utilizan para búsqueda, validación, extracción, sustitución, etc.

💡 Uso Básico

Creación de Regex

fun main() {
// Crear objeto Regex
val regex1 = Regex("hello")
val regex2 = "hello".toRegex()

// Verificar coincidencia
println(regex1.matches("hello")) // true
println(regex1.matches("Hello")) // false (distingue mayúsculas)
}

Coincidencia Simple

fun main() {
val text = "My email is hong@example.com"

// contains
val hasEmail = Regex("@").containsMatchIn(text)
println(hasEmail) // true

// find
val match = Regex("\\w+@\\w+\\.\\w+").find(text)
println(match?.value) // hong@example.com
}

🎯 Patrones Básicos

Clases de Caracteres

fun main() {
// \d - dígitos
println("123".matches(Regex("\\d+"))) // true

// \w - caracteres (letras, números, _)
println("hello_123".matches(Regex("\\w+"))) // true

// \s - espacios en blanco
println(" ".matches(Regex("\\s"))) // true

// . - cualquier carácter
println("abc".matches(Regex("..."))) // true (3 caracteres)
}

Cuantificadores

fun main() {
// + : 1 o más
println("aaa".matches(Regex("a+"))) // true

// * : 0 o más
println("".matches(Regex("a*"))) // true

// ? : 0 o 1
println("a".matches(Regex("a?"))) // true

// {n} : exactamente n
println("aaa".matches(Regex("a{3}"))) // true

// {n,m} : de n a m
println("aaa".matches(Regex("a{2,4}"))) // true
}

🎨 Ejemplos Prácticos

Validación de Email

fun isValidEmail(email: String): Boolean {
val pattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
return email.matches(pattern.toRegex())
}

fun main() {
println(isValidEmail("hong@example.com")) // true
println(isValidEmail("invalid.email")) // false
println(isValidEmail("test@domain.co.kr")) // true
}

Validación de Número de Teléfono

fun isValidPhone(phone: String): Boolean {
// 010-1234-5678 o 01012345678
val pattern = "010-?\\d{4}-?\\d{4}"
return phone.matches(pattern.toRegex())
}

fun main() {
println(isValidPhone("010-1234-5678")) // true
println(isValidPhone("01012345678")) // true
println(isValidPhone("02-1234-5678")) // false
}

Fortaleza de Contraseña

fun checkPasswordStrength(password: String): String {
val hasLength = password.length >= 8
val hasDigit = Regex("\\d").containsMatchIn(password)
val hasLower = Regex("[a-z]").containsMatchIn(password)
val hasUpper = Regex("[A-Z]").containsMatchIn(password)
val hasSpecial = Regex("[!@#$%^&*]").containsMatchIn(password)

return when {
hasLength && hasDigit && hasLower && hasUpper && hasSpecial -> "Muy fuerte"
hasLength && hasDigit && (hasLower || hasUpper) -> "Fuerte"
hasLength -> "Normal"
else -> "Débil"
}
}

fun main() {
println(checkPasswordStrength("Pass123!")) // Muy fuerte
println(checkPasswordStrength("password123")) // Fuerte
println(checkPasswordStrength("password")) // Normal
println(checkPasswordStrength("pass")) // Débil
}

Extracción de URLs

fun extractUrls(text: String): List<String> {
val pattern = "https?://[\\w./]+"
return Regex(pattern).findAll(text).map { it.value }.toList()
}

fun main() {
val text = """
Visit https://kotlin.org for info.
Check http://example.com too!
""".trimIndent()

val urls = extractUrls(text)
urls.forEach { println(it) }
// https://kotlin.org
// http://example.com
}

Extracción de Hashtags

fun extractHashtags(text: String): List<String> {
val pattern = "#\\w+"
return Regex(pattern).findAll(text).map { it.value }.toList()
}

fun main() {
val tweet = "오늘 날씨 좋네요 #날씨 #행복 #코틀린"
val hashtags = extractHashtags(tweet)

println("해시태그:")
hashtags.forEach { println(it) }
// #날씨
// #행복
// #코틀린
}

🔧 Funciones Avanzadas

Captura de Grupos

fun parseDate(text: String): Triple<String, String, String>? {
val pattern = "(\\d{4})-(\\d{2})-(\\d{2})"
val match = Regex(pattern).find(text) ?: return null

val (year, month, day) = match.destructured
return Triple(year, month, day)
}

fun main() {
val date = parseDate("Today is 2024-12-25")
if (date != null) {
val (year, month, day) = date
println("Year: $year, Month: $month, Day: $day")
}
}

Sustitución

fun main() {
val text = "My phone is 010-1234-5678"

// Enmascarar número de teléfono
val masked = text.replace(Regex("\\d{4}$"), "****")
println(masked) // My phone is 010-1234-****

// Múltiples espacios a uno
val multiSpace = "Hello World !"
val cleaned = multiSpace.replace(Regex("\\s+"), " ")
println(cleaned) // Hello World !
}

División

fun main() {
// Separar por coma o espacio
val text = "apple, banana orange,grape"
val fruits = text.split(Regex("[,\\s]+"))
println(fruits) // [apple, banana, orange, grape]

// Separar por números
val text2 = "item1,item2,item3"
val items = text2.split(Regex("\\d+"))
println(items) // [item, ,item, ,item, ]
}

🎯 Patrones Prácticos

Eliminar Etiquetas HTML

fun removeHtmlTags(html: String): String {
return html.replace(Regex("<[^>]*>"), "")
}

fun main() {
val html = "<p>Hello <b>World</b>!</p>"
val text = removeHtmlTags(html)
println(text) // Hello World!
}

Extracción de Números

fun extractNumbers(text: String): List<Int> {
return Regex("\\d+").findAll(text)
.map { it.value.toInt() }
.toList()
}

fun main() {
val text = "I have 3 apples and 5 oranges"
val numbers = extractNumbers(text)
println(numbers) // [3, 5]
}

Formateo de Moneda

fun formatCurrency(amount: Int): String {
return amount.toString().replace(Regex("(\\d)(?=(\\d{3})+$)"), "$1,")
}

fun main() {
println(formatCurrency(1000)) // 1,000
println(formatCurrency(1234567)) // 1,234,567
}

🤔 Preguntas Frecuentes

P1. ¿Cómo ignorar mayúsculas y minúsculas?

R: Use RegexOption!

fun main() {
val regex = Regex("hello", RegexOption.IGNORE_CASE)

println(regex.matches("Hello")) // true
println(regex.matches("HELLO")) // true
println(regex.matches("hello")) // true
}

P2. ¿Cómo escapar caracteres?

R: Use dos barras invertidas!

fun main() {
// Coincidir . literalmente
val dotRegex = Regex("\\.")
println("3.14".contains(dotRegex)) // true

// ( ) literalmente
val parens = Regex("\\(.*\\)")
println("(test)".matches(parens)) // true
}

P3. ¿Qué hay del rendimiento?

R: Reutilice Regex compilados!

// ❌ Compilar cada vez
fun bad(text: String): Boolean {
return text.matches(Regex("\\d+")) // lento
}

// ✅ Compilar una sola vez
val NUMBER_REGEX = Regex("\\d+")
fun good(text: String): Boolean {
return text.matches(NUMBER_REGEX) // rápido
}

📚 Resumen de Patrones Principales

Caracteres:
^ - inicio
$ - fin
. - cualquier carácter
\d - dígito [0-9]
\D - no dígito
\w - carácter [a-zA-Z0-9_]
\W - no carácter
\s - espacio en blanco
\S - no espacio en blanco

Cantidad:
* - 0 o más
+ - 1 o más
? - 0 o 1
{n} - exactamente n
{n,} - n o más
{n,m} - de n a m

Grupos:
(...) - grupo
| - OR
[abc] - uno de a, b, c
[^abc] - no a, b, c
[a-z] - de a a z

🎬 Conclusión

¡Procesamiento de cadenas poderoso con expresiones regulares!

Puntos clave:
✅ Crear patrones con Regex()
✅ Coincidencia completa con matches()
✅ Coincidencia parcial con find()
✅ Sustitución con replace()
✅ Mejorar rendimiento reutilizando patrones

Siguiente paso: En DSL, cree APIs al estilo de Kotlin.