liveBook · Manning

Regular expression

As explained in Kotlin in Action, 2E

A regular expression is a pattern language for matching, searching, or transforming text according to character and repetition rules.

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

How Kotlin in Action, 2E covers it

How deep it goes
Explains wildcard matching, escaping, groups, and Kotlin matching calls, but stops short of broader pattern mechanics.
Examples
Uses dot-or-dash splitting and directory, filename, and extension extraction from a full path.
What it assumes
Assumes basic Kotlin and string familiarity while teaching pattern escaping, Regex conversion, groups, and match results.
What you can do after
Apply regular expressions in Kotlin to split strings and extract path components from successful matches.
How it connects
Connects regular expressions with Kotlin strings, extension functions, Java regular expressions, triple-quoted strings, and destructuring declarations.

Also explained in

Compare how 27 books explain regular expression →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.