🔍 正規表現
📖 正規表現とは?
**正規表現(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
}