Skip to content
Mark Whitaker edited this page Aug 18, 2019 · 4 revisions

Contents

Overview

Groups are used in a regex for one (or both) of two purposes:

  1. To group a number of elements together so a quantifier can be applied to the whole group.
  2. To "remember" part of the text matched by the regex so we can extract it later using the groups and groupValues properties of the kotlin.text.MatchResult class.

Grouping elements for quantifiers

Grouping for quantifiers is pretty self-explanatory. A quantifier passed to the endGroup() method will apply to the whole group. For example, this is a very simple regex to match a normal sentence:

val regex = RegexBuilder()
    .startGroup()
        .wordCharacter(RegexQuantifier.oneOrMore())
        .whitespace(RegexQuantifier.oneOrMore())
    .endGroup(RegexQuantifier.oneOrMore())
    .wordCharacter(RegexQuantifier.oneOrMore())
    .text(".")
    .buildRegex()

Remembering parts of the match

Say we want to match a person's name (two consecutive words each beginning with a capital letter) and then greet them by their first name, we could build a regex like this:

val regex = RegexBuilder()
    .wordBoundary()
    .startGroup()
        .uppercaseLetter()
        .lowercaseLetter(RegexQuantifier.oneOrMore())
    .endGroup()
    .whitespace()
    .uppercaseLetter()
    .lowercaseLetter(RegexQuantifier.oneOrMore())
    .wordBoundary()
    .buildRegex()

We can then extract the first name from a successful match like this:

val firstName = regex.find(inputString)?.groupValues[1]

Note that groupValues() is indexed from 1, not 0. For reasons documented elsewhere, groupValues(0) will return the whole matched string.

Named groups

If you prefer to avoid numerical indices altogether you can also define named groups which are then indexed by name. Using named groups, our code would look like this:

val regex = RegexBuilder()
    .wordBoundary()
    .startNamedGroup("firstName")
        .uppercaseLetter()
        .lowercaseLetter(RegexQuantifier.oneOrMore())
    .endGroup()
    .whitespace()
    .uppercaseLetter()
    .lowercaseLetter(RegexQuantifier.oneOrMore())
    .wordBoundary()
    .buildRegex()

val firstName = regex.find(inputString)?.groups["firstName"]?.value

Nesting groups

As with raw regexes, RegexBuilder allows you to nest groups to arbitrary depth. If you use capturing groups, matchResult?.groupValues[1] will refer to the first started group, and so on. For example:

val regex = RegexBuilder()
    .wordBoundary()
    .startGroup()                          // start of group 1
        .startGroup()                      // start of group 2
            .uppercaseLetter()
        .endGroup()                        // end of group 2
        .lowercaseLetter(RegexQuantifier.oneOrMore())
    .endGroup(RegexQuantifier.oneOrMore()) // end of group 1
    .wordBoundary()
    .buildRegex()

val matchResult = regex.find("sorry Dave, I can't do that")
val name = matchResult?.groupValues[1]    // "Dave"
val initial = matchResult?.groupValues[2] // "D"

Methods

Method Description Raw regex equivalent
startGroup() Start a group which can be extracted later by calling MatchResult.groupValues[index: Int]. (
startNamedGroup(name: String) Start a group which can be extracted later by calling MatchResult.groups[index: String].value . (?<name>
startNonCapturingGroup() Start a group which cannot be extracted later with MatchResult.groups or MatchResult.groupValues. This can be useful if you have more than one group in a regex, and you don't want to a group that's purely for quantifiers to disrupt the indices of your capturing groups. (?:
endGroup() End the current group (the innermost group in the case of nested groups), optionally specifying a quantifier for the group. )

Download from JitPack

Clone this wiki locally