Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 134 ยท Text, Files and Time

Regular Expressions

Learn Kotlin regular expressions - the Regex class, containsMatchIn, find, findAll, matchEntire, groups, named groups, replace with lambdas, split and Regex.escape - with runnable examples.

A regular expression (regex) is a small pattern language for describing text: "three digits, a dash, then four digits", "a word followed by an equals sign", "anything that looks like an email address". Instead of writing a loop that walks through characters and keeps track of state, you describe the shape of the text you want and let the regex engine search for it. Regexes are good at validating input, pulling pieces out of messy text and doing smart find-and-replace. They are also easy to overuse, and this lesson will show you where to stop.

Kotlin has no special regex syntax. A pattern is a string, and the standard library wraps it in the class Regex, which sits on top of Java's java.util.regex engine. So the pattern language is the one you may know from Java, and everything you learn here works the same on the JVM anywhere. What Kotlin adds is a friendlier API: results are nullable instead of throwing, matches are Sequences, and replace accepts a lambda.

Creating a Regex

You create a Regex from a string, usually a raw string ("""...""") because patterns are full of backslashes. In a normal string, \d is an invalid escape; you would have to write "\\d". In a raw string, a backslash is just a backslash.

Kotlin Creating a Regex and testing a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

containsMatchIn answers "does this pattern occur anywhere in the text?". The text does not have to match completely, only a part of it. Printing a Regex shows its pattern. RegexOption values such as IGNORE_CASE, MULTILINE and DOT_MATCHES_ALL change how the pattern behaves; you can pass one or a set of them.

A Regex is immutable and thread-safe, but compiling a pattern costs time. If you use the same pattern many times, create it once (in a top-level val or a companion object), not inside a loop or a function that is called often.

A quick tour of the pattern language

You do not need to memorize everything, but these building blocks cover most real patterns:

Pattern Meaning
. any character except a line break
\d, \w, \s a digit, a "word" character (letter, digit, underscore), whitespace
\D, \W, \S the opposite of the above
[abc], [a-z], [^0-9] one of the listed characters, a range, anything but these
*, +, ? zero or more, one or more, zero or one of the previous item
, {2,4} exactly 3, between 2 and 4 of the previous item
^, $ start and end of the text (or of each line with MULTILINE)
\b a word boundary
(...) a capturing group
a|b a or b

Quantifiers are greedy by default: they take as much as they can. Adding ? after them (*?, +?) makes them lazy, taking as little as possible. This difference causes many surprises, so we will test it below.

find and findAll

find returns the first match as a MatchResult?, which is null when nothing matches. findAll returns a lazy Sequence<MatchResult> of all non-overlapping matches. A MatchResult has value (the matched text) and range (where it was found).

Kotlin find and findAll

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Because findAll is a sequence, nothing is searched until you consume it. first() stops at the first match; toList() collects everything. Note that \d+ matched 2026, 03 and 09 as separate numbers inside the dates. A pattern matches what you describe, not what you meant.

matchEntire: the whole string or nothing

containsMatchIn and find look for a match inside the text. For validation you usually need the opposite: the whole string must fit the pattern. matchEntire does exactly that, and matches is the boolean version.

Kotlin matchEntire versus containsMatchIn

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

902101 contains five digits, so containsMatchIn says yes, but it is not five digits in total, so matches says no. This is one of the most common regex bugs: validating with containsMatchIn (or Java's find) and accidentally accepting garbage around a valid piece. Use matches or matchEntire for validation, or anchor the pattern with ^ and $.

Groups: pulling pieces out

Parentheses create capturing groups. After a match, groupValues is a list of strings: index 0 is the whole match, index 1 is the first group, and so on. A group that did not take part in the match gives an empty string in groupValues; use groups[i] when you need to tell "empty" from "absent", because it returns MatchGroup?.

Kotlin Capturing groups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

destructured gives you the groups as components, so val (year, month, day) = ... reads nicely. Groups are always strings, so convert them yourself with toInt() or toIntOrNull(). The group (?:...) is non-capturing: it groups for the purpose of the ? but takes no number, which keeps your numbering stable.

Named groups

Counting parentheses breaks the moment someone adds a group at the front of the pattern. Named groups ((?<name>...)) let you access groups by name instead, through groups["name"].

Kotlin Named groups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The named-group lookup returns MatchGroup? and is null for the optional label when it is missing. Wrapping the parsing in a function that returns Version? keeps the messy regex in one place; callers only see a typed value or null. Group names must be letters and digits and start with a letter, and you can also refer to them inside replace as ${name}.

replace and replace with a lambda

replace(input, replacement) swaps every match for a string. In the replacement, $1 or ${name} insert a captured group, and a literal dollar sign must be written as \$. If you need logic, pass a lambda that receives the MatchResult and returns the replacement. replaceFirst changes only the first match.

Kotlin replace, with groups and with a lambda

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The named-reference line looks odd because in a Kotlin string ${...} is a template; ${'$'} writes a literal dollar sign. In a raw string the same trick is needed. When you find yourself escaping dollars, a lambda is usually cleaner: date.replace(text) { it.groups["d"]!!.value + "/" + it.groups["m"]!!.value }.

split with a regex

String.split accepts a Regex, so you can split on "one or more of any whitespace or comma" instead of one fixed character.

Kotlin Splitting on a pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first call, with a plain string, leaves empty and padded pieces. The regex [,;\s]+ treats any run of separators as one. If the text starts or ends with a separator, you get an empty string at that end; combine with filter { it.isNotEmpty() } or trim() when that matters.

Greedy and lazy quantifiers

A greedy .* runs to the end of the line and then backs off until the rest of the pattern fits. In text like HTML tags, this finds one giant match instead of several small ones.

Kotlin Greedy versus lazy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The greedy version grabs everything from the first < to the last >. Both the lazy .+? and the negated class [^>]+ (any character except >) find the individual tags. Prefer the negated class when you can: it says exactly what you mean and it is faster, because the engine does not have to back off.

Regex.escape: user text inside a pattern

Characters such as ., *, ( and $ have special meaning. If you want to search for a literal string that comes from a user or a file, you must not paste it into the pattern unchanged. Regex.escape turns text into a pattern that matches that text literally. (The related Regex.escapeReplacement does the same for the replacement string.)

Kotlin Searching for literal text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The unescaped 1+1 means "one or more 1s followed by a 1", which does not appear in the text, so the answer is surprising. Escaping fixes it. The last line is the real lesson: if you want a literal match, you do not need a regex at all. contains, indexOf, startsWith and replace on strings are simpler and faster.

Bad patterns fail at construction

An invalid pattern throws PatternSyntaxException the moment you create the Regex, not when you use it. For patterns written in your source code, that happens on the first run, which is easy to catch. For patterns that come from users, wrap the creation in runCatching or a try block.

Kotlin An invalid pattern (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first line demonstrates the safe way. The second pattern is not wrapped, so the program ends with an uncaught java.util.regex.PatternSyntaxException (message: Unclosed character class near index 3) and exit code 1.

When not to use a regex

Regexes are a tool, not a goal. Skip them when:

  • a plain function does the job (startsWith, contains, split(","), toIntOrNull());
  • the format is nested or recursive (HTML, JSON, source code): use a real parser, because regexes cannot count nesting;
  • the pattern is too long to read. If nobody can explain it, split it into steps, or build it from named pieces with string templates;
  • the input is untrusted and the pattern has nested quantifiers like (a+)+: such patterns can take exponential time on crafted input ("catastrophic backtracking"). Keep patterns simple, limit the input length, and test with long near-matches.

Related lessons: Strings for the plain string functions, Text Processing for splitting and parsing, Sequences for how lazy findAll works, and Destructuring Pairs and Triples for the val (a, b) = ... form used with groups.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You want to check that a whole string is exactly five digits. Which call is correct?

    matches (and matchEntire) require the whole string to match. containsMatchIn and find accept five digits anywhere, so '902101' would pass.
  2. 2. What does find return when the text contains no match?

    find returns a nullable MatchResult?, so null means no match. That fits well with ?. and the Elvis operator.
  3. 3. Given Regex("""(\d+)-(\d+)""").find("10-20"), what is groupValues[0]?

    Index 0 of groupValues is the entire match. The groups themselves start at index 1.
  4. 4. Why is Regex.escape useful?

    Special characters such as + . ( and $ would otherwise be interpreted as pattern syntax. Regex.escape wraps the text so that it matches literally.
  5. 5. What is the difference between <.+> and <.+?> on <b>x</b>?

    .+ is greedy and takes as much as possible, up to the last >. The lazy .+? takes as little as possible, stopping at the first >.

Summary

  • Regex wraps Java's regex engine; write patterns as raw strings ("""\d+""") to avoid doubled backslashes, and create reused patterns once.
  • containsMatchIn and find search inside text; matches and matchEntire require the whole string to fit. Use the latter for validation.
  • find returns MatchResult?; findAll returns a lazy Sequence. groupValues[0] is the whole match, groups start at 1; destructured and named groups (groups["name"]) make extraction readable.
  • replace supports $1 and ${name} references or a lambda; split accepts a Regex.
  • Quantifiers are greedy by default; use ? for lazy or a negated class like [^>]+.
  • Regex.escape makes user text literal; an invalid pattern throws PatternSyntaxException at construction.
  • Do not use a regex when a string function or a real parser fits better.

Next: Text Processing