toPattern
Converts the string into a regular expression Pattern optionally with the specified flags from Pattern or'd together so that strings can be split or matched on.
Since Kotlin
1.0Samples
import kotlin.test.*
import java.util.*
import java.util.regex.*
fun main() {
//sampleStart
val string = "Kotlin [1-9]+\\.[0-9]\\.[0-9]+"
val pattern = string.toPattern(Pattern.CASE_INSENSITIVE)
println(pattern.pattern()) // string
println("pattern.flags() == Pattern.CASE_INSENSITIVE is ${pattern.flags() == Pattern.CASE_INSENSITIVE}") // true
println("pattern.matcher(\"Kotlin 2.1.255\").matches() is ${pattern.matcher("Kotlin 2.1.255").matches()}") // true
println("pattern.matcher(\"kOtLiN 21.0.1\").matches() is ${pattern.matcher("kOtLiN 21.0.1").matches()}") // true
println("pattern.matcher(\"Java 21.0.1\").matches() is ${pattern.matcher("Java 21.0.1").matches()}") // false
println("pattern.matcher(\"Kotlin 2.0\").matches() is ${pattern.matcher("Kotlin 2.0").matches()}") // false
// the given regex is malformed
// "[0-9".toPattern(Pattern.CASE_INSENSITIVE) // will fail
//sampleEnd
}