<!--
{
  "availability" : [
    "iOS: 16.0.0 -",
    "iPadOS: 16.0.0 -",
    "macCatalyst: 16.0.0 -",
    "macOS: 13.0.0 -",
    "tvOS: 16.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 9.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/Regex/firstMatch(in:)-6s8x0",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:17_StringProcessing5RegexV10firstMatch2inAC0E0Vyx_GSgSS_tKF"
  },
  "title" : "firstMatch(in:)"
}
-->

# firstMatch(in:)

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

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

## Parameters

`string`

The string to match this regular expression against.

## Return Value

The match, if one is found; otherwise, `nil`.

## 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.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)