To replace all occurrences of a substring in a string using regular expression in Swift, you can use the replacingOccurrences
method of the String
class with a regex pattern.
In this example,
str
.str
with "Hi" using replacingOccurrences
method.import Foundation
let str = "Hello World Hello"
let newStr = str.replacingOccurrences(of: "Hello", with: "Hi", options: .regularExpression)
print(newStr)
Hi World Hi
In this example,
str
.str
with 'Y' using replacingOccurrences
method.import Foundation
let str = "Hello123World789"
let newStr = str.replacingOccurrences(of: "\\d", with: "Y", options: .regularExpression)
print(newStr)
HelloYYYWorldYYY
In this tutorial, we learned How to Replace a Substring in a String using Regular Expression in Swift language with well detailed examples.