← Retour

Rechercher avec des accents en Java / Kotlin JVM

~1 min

On va voir comment rechercher sans tenir compte des accents en Java / Kotlin JVM

Un petit article pour faire gagner du temps à ceux qui comme moi voient un paquets de solutions différentes pour ce problème typiquement pas anglais.

Problème

On veut pouvoir rechercher sans distinction de casse et d’accents.

“Café” et “cafe” doivent être considérés comme identiques.

Solution

fun String.removeAccentsAndNormalize(): String {
    val normalizedText = Normalizer.normalize(this, Normalizer.Form.NFD)
    val pattern = "\\p{InCombiningDiacriticalMarks}+".toRegex()
    return pattern.replace(normalizedText, "")
}

Après il devient simple de comparer avec un contains ou un startsWith par exemple.

fun searchInTitle(title: String?, query: String): Boolean {
    query.removeAccentsAndNormalize()
    return title?.contains(query, ignoreCase = true) ?: false
}

Si vous êtes sur Android

On doit rajouter un petit test et utiliser le Normalizer2 à partir de la version 24 d’Android.

fun String.removeAccentsAndNormalize(): String {
    
    val normalizedText = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Normalizer2.getNFDInstance().normalize(this)
    } else {
        Normalizer.normalize(this, Normalizer.Form.NFD)
    }
    val pattern = "\\p{InCombiningDiacriticalMarks}+".toRegex()
    return pattern.replace(normalizedText, "")
}

Have a nice day !