0Pricing
Swift Academy · Lesson

Capturing Groups

Extract substrings from matches.

Capturing Groups is a free Swift Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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)")
}

Multiple Captures

Each pair of parentheses adds another element to the output tuple, in left-to-right order.

if let m = "2024-05-30".wholeMatch(of: /(\d{4})-(\d{2})-(\d{2})/) {
    print("Year: \(m.1)")
    print("Month: \(m.2)")
    print("Day: \(m.3)")
}

The Whole Match is .0

Element .0 of the output is always the entire matched text. Captures start at .1.

if let m = "key=value".wholeMatch(of: /(\w+)=(\w+)/) {
    print("Full: \(m.0)")
    print("Key: \(m.1), Value: \(m.2)")
}

Captures Are Substrings

By default captures are Substring values that point into the original string. Convert with String(...) if you need to keep them.

if let m = "abc123".firstMatch(of: /([a-z]+)(\d+)/) {
    let letters = String(m.1)
    let numbers = String(m.2)
    print(letters, numbers)
}

Optional Captures

If a group is optional (followed by ?), its capture may be nil when it did not participate in the match.

if let m = "color".wholeMatch(of: /colou?(r)/) {
    print("Captured: \(m.1)")
}

Named Captures

You can name a group with (?<name>...) and read it via the named output, which is clearer than numeric indices.

let re = /(?<area>\d{3})-(?<line>\d{4})/
if let m = "555-1234".wholeMatch(of: re) {
    print("Area: \(m.area)")
    print("Line: \(m.line)")
}

Iterating Captures

Combine captures with matches(of:) to extract structured data from many matches at once.

let log = "a=1 b=2 c=3"
for m in log.matches(of: /(\w+)=(\d+)/) {
    print("\(m.1) -> \(m.2)")
}

Nested Groups

Groups can nest. The outer group captures the whole, inner groups capture parts. Numbering follows the order of opening parentheses.

if let m = "12:30".wholeMatch(of: /((\d+):(\d+))/) {
    print("All: \(m.1)")
    print("H: \(m.2), M: \(m.3)")
}

Non-Capturing Groups

Use (?:...) to group without capturing, when you only need grouping for a quantifier and do not want an extra tuple element.

if let m = "abab".wholeMatch(of: /(?:ab)+/) {
    print("Matched: \(m.0)")
}

Building a Parser

Captures turn raw text into typed values. Here we parse a coordinate string into integers.

func parsePoint(_ s: String) -> (Int, Int)? {
    guard let m = s.wholeMatch(of: /(\d+),(\d+)/),
          let x = Int(m.1), let y = Int(m.2) else { return nil }
    return (x, y)
}
print(parsePoint("3,7") ?? "nil")

Quick Check

For pattern /(\d{4})-(\d{2})/ matching "2024-05", what is m.2?

Recap

Parentheses create capturing groups accessible as a tuple where .0 is the whole match and .1, .2... are captures. You saw named, optional, nested, and non-capturing groups. Next you will build regexes from readable Swift code with RegexBuilder.

Frequently asked questions

Is the “Capturing Groups” lesson free?

Yes — the full text of “Capturing Groups” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Capturing Groups”?

Extract substrings from matches. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Capturing Groups” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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