Passer au contenu principal

🔍 Expressions régulières

📖 Qu'est-ce qu'une expression régulière ?

Les expressions régulières (Regular Expression, Regex) sont une méthode pour exprimer des motifs de chaînes. Elles sont utilisées pour la recherche, la validation, l'extraction, le remplacement, etc. !

💡 Utilisation de base

Création d'une Regex

fun main() {
// Regex 객체 생성
val regex1 = Regex("hello")
val regex2 = "hello".toRegex()

// 매칭 확인
println(regex1.matches("hello")) // true
println(regex1.matches("Hello")) // false (대소문자 구분)
}

Correspondance 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
}

🎯 Motifs de base

Classes de caractères

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

// \w - 문자 (영문, 숫자, _)
println("hello_123".matches(Regex("\\w+"))) // true

// \s - 공백
println(" ".matches(Regex("\\s"))) // true

// . - 아무 문자
println("abc".matches(Regex("..."))) // true (3글자)
}

Quantificateurs

fun main() {
// + : 1개 이상
println("aaa".matches(Regex("a+"))) // true

// * : 0개 이상
println("".matches(Regex("a*"))) // true

// ? : 0개 또는 1개
println("a".matches(Regex("a?"))) // true

// {n} : 정확히 n개
println("aaa".matches(Regex("a{3}"))) // true

// {n,m} : n개 이상 m개 이하
println("aaa".matches(Regex("a{2,4}"))) // true
}

🎨 Exemples pratiques

Validation d'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
}

Validation de numéro de téléphone

fun isValidPhone(phone: String): Boolean {
// 010-1234-5678 또는 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
}

Force du mot de passe

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 -> "Très fort"
hasLength && hasDigit && (hasLower || hasUpper) -> "Fort"
hasLength -> "Moyen"
else -> "Faible"
}
}

fun main() {
println(checkPasswordStrength("Pass123!")) // Très fort
println(checkPasswordStrength("password123")) // Fort
println(checkPasswordStrength("password")) // Moyen
println(checkPasswordStrength("pass")) // Faible
}

Extraction d'URL

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
}

Extraction 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) }
// #날씨
// #행복
// #코틀린
}

🔧 Fonctionnalités avancées

Capture de groupes

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")
}
}

Remplacement

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

// 전화번호 마스킹
val masked = text.replace(Regex("\\d{4}$"), "****")
println(masked) // My phone is 010-1234-****

// 여러 공백을 하나로
val multiSpace = "Hello World !"
val cleaned = multiSpace.replace(Regex("\\s+"), " ")
println(cleaned) // Hello World !
}

Division

fun main() {
// 쉼표나 공백으로 분리
val text = "apple, banana orange,grape"
val fruits = text.split(Regex("[,\\s]+"))
println(fruits) // [apple, banana, orange, grape]

// 숫자로 분리
val text2 = "item1,item2,item3"
val items = text2.split(Regex("\\d+"))
println(items) // [item, ,item, ,item, ]
}

🎯 Motifs pratiques

Suppression des balises 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!
}

Extraction de nombres

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]
}

Formatage de montants

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
}

🤔 Questions fréquentes

Q1. Comment ignorer la casse ?

R : Utilisez 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
}

Q2. Comment échapper les caractères spéciaux ?

R : Utilisez deux barres obliques inverses !

fun main() {
// . 을 문자 그대로 매칭
val dotRegex = Regex("\\.")
println("3.14".contains(dotRegex)) // true

// ( ) 을 문자 그대로
val parens = Regex("\\(.*\\)")
println("(test)".matches(parens)) // true
}

Q3. Qu'en est-il des performances ?

R : Réutilisez les Regex compilées !

// ❌ 매번 컴파일
fun bad(text: String): Boolean {
return text.matches(Regex("\\d+")) // 느림
}

// ✅ 한 번만 컴파일
val NUMBER_REGEX = Regex("\\d+")
fun good(text: String): Boolean {
return text.matches(NUMBER_REGEX) // 빠름
}

📚 Résumé des motifs principaux

Caractères :
^ - Début
$ - Fin
. - N'importe quel caractère
\d - Chiffre [0-9]
\D - Non-chiffre
\w - Caractère [a-zA-Z0-9_]
\W - Non-caractère
\s - Espace blanc
\S - Non-espace blanc

Quantité :
* - 0 ou plus
+ - 1 ou plus
? - 0 ou 1
{n} - Exactement n
{n,} - n ou plus
{n,m} - Entre n et m

Groupes :
(...) - Groupe
| - OU
[abc] - a, b ou c
[^abc] - Ni a, ni b, ni c
[a-z] - De a à z

🎬 Conclusion

Réalisez un traitement puissant des chaînes avec les expressions régulières !

Récapitulatif :
✅ Créez des motifs avec Regex()
✅ Correspondance complète avec matches()
✅ Correspondance partielle avec find()
✅ Remplacement avec replace()
✅ Améliorez les performances en réutilisant les motifs

Prochaine étape : Dans DSL, créez des API dans le style Kotlin !