0Pricing
Swift Academy · Lesson

Capturing Groups

Extract substrings from matches.

Capturing Groups

Parentheses in a regex create capturing groups. Each group remembers the substring it matched, so you can extract structured pieces from a larger match.

A Single Capture

Wrapping part of a pattern in () captures it. The match output becomes a tuple: the whole match first, then each capture.

if let m = "v2".firstMatch(of: /v(\d+)/) {
    print("Whole: \(m.0)")
    print("Group: \(m.1)")
}

All lessons in this course

  1. Regex Literals and Matching
  2. Capturing Groups
  3. RegexBuilder DSL
  4. Replacing and Splitting Text
← Back to Swift Academy