A regular expression is a pattern for matching text according to character and repetition rules. Kotlin uses Java’s syntax, while its APIs make the distinction between plain text and patterns explicit. section 3.5.1
fun main() {
println("12.345-6.A".split("\\.|-".toRegex())) #1
// [12, 345, 6, A]
}
Split a string on either a literal dot or a dash by converting the pattern to Regex; escape the dot because it otherwise matches any character. section 3.5.1
Use regular expressions deliberately:
- Write "\\.|-".toRegex() when the delimiters are pattern-based; Kotlin’s overload requires Regex or Pattern rather than silently treating a String as a pattern. section 3.5.1
- Prefer plain-text split('.', '-') for simple delimiters; it is clearer and avoids unnecessary pattern syntax. section 3.5.1
- Use triple-quoted strings for complex patterns when possible; a literal dot can be written as \., without escaping the backslash for the Kotlin string literal. section 3.5.2
Parsing a file path
val regex = """(.+)/(.+)\.(.+)""".toRegex() val matchResult = regex.matchEntire(path) if (matchResult != null) { val (directory, filename, extension) = matchResult.destructured } The three groups capture the directory, filename, and extension. For /Users/yole/kotlin-book/chapter.adoc, they produce /Users/yole/kotlin-book, chapter, and adoc. The same task can be simpler with substringBeforeLast and substringAfterLast. section 3.5.2


























