Normalizar un texto en Kotlin
normalizar un texto

Normalizar un texto en Kotlin

Para quitarle los caracteres especiales a un texto en Kotlin, podemos usar la función normalize().

Esto puede ser muy útil para por ejemplo hacer un filtro de búsqueda.

Aquí te dejo un ejemplo:

fun String.normalizeText(): String {
    val temp = Normalizer.normalize(lowercase(Locale.US), Normalizer.Form.NFD)
    return REGEX_UNACCENT.replace(temp, "")
}

private val REGEX_UNACCENT = "\\p{InCombiningDiacriticalMarks}+".toRegex()

¿Y cómo podríamos testearlo?

Muy fácil:

class NormalizeTextKtTest {

    @Test
    fun `GIVEN a normal text WHEN normalizeText THEN return the proper string`() {
        val givenText = "aeiou"
        val expectedText = "aeiou"

        val result = givenText.normalizeText()

        result shouldBeEqualTo expectedText
    }

    @Test
    fun `GIVEN a weird text WHEN normalizeText THEN return the proper string`() {
        val givenText = "áéíóúàèìòùäëïöüAEIOUñ"
        val expectedText = "aeiouaeiouaeiouaeioun"

        val result = givenText.normalizeText()

        result shouldBeEqualTo expectedText
    }
}

Publicado: 2022-08-14 Actualizado: 2023-09-19