---
title: "firstMatch(in:)"
framework: swift
role: symbol
role_heading: Instance Method
path: "swift/regex/firstmatch(in:)-45hz7"
---

# firstMatch(in:)

Returns the first match for this regex found in the given substring.

## Declaration

```swift
func firstMatch(in string: Substring) throws -> Regex<Output>.Match?
```

## Parameters

- `string`: The substring to match this regular expression against.

## Return Value

Return Value The match, if one is found; otherwise, nil.

## Discussion

Discussion Use the firstMatch(in:) method to search for the first occurrence of this regular expression in string. This example searches for the first sequence of digits that occurs in a string: let digits = /[0-9]+/

if let digitsMatch = try digits.firstMatch(in: "The year is 2022; last year was 2021.") {     print(digitsMatch.0) } else {     print("No match.") } // Prints "2022" The firstMatch(in:) method can throw an error if this regex includes a transformation closure that throws an error.
