<!--
{
  "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",
  "metadataVersion" : "0.1.0",
  "role" : "Structure",
  "symbol" : {
    "kind" : "Structure",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:17_StringProcessing5RegexV"
  },
  "title" : "Regex"
}
-->

# Regex

A regular expression.

```
struct Regex<Output>
```

## Overview

Regular expressions are a concise way of describing a pattern, which can
help you match or extract portions of a string. You can create a `Regex`
instance using regular expression syntax, either in a regex literal or a
string.

```
// 'keyAndValue' is created using a regex literal
let keyAndValue = /(.+?): (.+)/
// 'simpleDigits' is created from a pattern in a string
let simpleDigits = try Regex("[0-9]+")
```

You can use a `Regex` to search for a pattern in a string or substring.
Call `contains(_:)` to check for the presence of a pattern, or
`firstMatch(of:)` or `matches(of:)` to find matches.

```
let setting = "color: 161 103 230"
if setting.contains(simpleDigits) {
    print("'\(setting)' contains some digits.")
}
// Prints "'color: 161 103 230' contains some digits."
```

When you find a match, the resulting [`Regex.Match`](/documentation/Swift/Regex/Match) type includes an
[`output`](/documentation/Swift/Regex/Match/output) property that contains the matched substring along with
any captures:

```
if let match = setting.firstMatch(of: keyAndValue) {
    print("Key: \(match.1)")
    print("Value: \(match.2)")
}
// Key: color
// Value: 161 103 230
```

When you import the `RegexBuilder` module, you can also create `Regex`
instances using a clear and flexible declarative syntax. Using this
style, you can combine, capture, and transform regexes, `RegexBuilder`
types, and custom parsers.

> Note:
> Prior to Swift 6,
> you might need to write `#/myregex/#` instead of `/myregex/`
> when you make a regular expression using a literal.
> For more information,
> see [Regular Expression Literals](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/lexicalstructure/#Regular-Expression-Literals) in  *[The Swift Programming Language](https://docs.swift.org/swift-book/)*.

---

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)
