メインコンテンツにスキップ

🔍 正規表現

📖 正規表現とは?

**正規表現(Regular Expression, Regex)**は文字列パターンを表現する方法です。検索、検証、抽出、置換などに使用します!

💡 基本的な使い方

Regex生成

fun main() {
// Regexオブジェクト生成
val regex1 = Regex("hello")
val regex2 = "hello".toRegex()

// マッチング確認
println(regex1.matches("hello")) // true
println(regex1.matches("Hello")) // false (大文字小文字を区別)
}

簡単なマッチング

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
}

🎯 基本パターン

文字クラス

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文字)
}

量指定子

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
}

🎨 実践例

メール検証

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
}

電話番号検証

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
}

パスワード強度

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 -> "非常に強い"
hasLength && hasDigit && (hasLower || hasUpper) -> "強い"
hasLength -> "普通"
else -> "弱い"
}
}

fun main() {
println(checkPasswordStrength("Pass123!")) // 非常に強い
println(checkPasswordStrength("password123")) // 強い
println(checkPasswordStrength("password")) // 普通
println(checkPasswordStrength("pass")) // 弱い
}

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
}

ハッシュタグ抽出

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

🔧 高度な機能

グループキャプチャ

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

置換

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

// 電話番号マスキング
val masked = text.replace(Regex("\\d{4}$"), "****")
println(masked) // My phone is 010-1234-****

// 複数の空白を1つに
val multiSpace = "Hello World !"
val cleaned = multiSpace.replace(Regex("\\s+"), " ")
println(cleaned) // Hello World !
}

分割

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

🎯 実用パターン

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

数字抽出

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

金額フォーマット

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
}

🤔 よくある質問

Q1. 大文字小文字を無視するには?

A: 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. エスケープは?

A: バックスラッシュを2つ!

fun main() {
// . を文字通りマッチング
val dotRegex = Regex("\\.")
println("3.14".contains(dotRegex)) // true

// ( ) を文字通り
val parens = Regex("\\(.*\\)")
println("(test)".matches(parens)) // true
}

Q3. パフォーマンスは?

A: コンパイル済みRegexを再利用します!

// ❌ 毎回コンパイル
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) // 速い
}

📚 主要パターンまとめ

文字:
^ - 開始
$ - 終了
. - 任意の文字
\d - 数字 [0-9]
\D - 数字以外
\w - 文字 [a-zA-Z0-9_]
\W - 文字以外
\s - 空白
\S - 空白以外

数量:
* - 0個以上
+ - 1個以上
? - 0個または1個
{n} - 正確にn個
{n,} - n個以上
{n,m} - n個以上m個以下

グループ:
(...) - グループ
| - OR
[abc] - a, b, cのいずれか
[^abc] - a, b, c以外
[a-z] - aからzまで

🎬 最後に

正規表現で強力な文字列処理を!

重要ポイント:
✅ Regex()でパターン生成
✅ matches()で全体マッチング
✅ find()で部分マッチング
✅ replace()で置換
✅ パターン再利用でパフォーマンス向上

次のステップ: DSLでKotlinらしいAPIを作ってみましょう!