<!--
{
  "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/RangeReplaceableCollection/replace(_:with:maxReplacements:)-20ctz",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:Sm17_StringProcessingSs11SubSequenceRtzrlE7replace_4with15maxReplacementsyqd_0__qd__SitSlRd__AA14RegexComponentRd_0_SJ7ElementRtd__r0_lF"
  },
  "title" : "replace(_:with:maxReplacements:)"
}
-->

# replace(_:with:maxReplacements:)

Replaces all occurrences of the sequence matching the given regex with
a given collection.

```
mutating func replace<Replacement>(_ regex: some RegexComponent, with replacement: Replacement, maxReplacements: Int = .max) where Replacement : Collection, Replacement.Element == Character
```

## Parameters

`regex`

A regex describing the sequence to replace.

`replacement`

The new elements to add to the collection.

`maxReplacements`

A number specifying how many occurrences of the
sequence matching `regex` to replace. Default is `Int.max`.

---

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)