Swift:
Searching and replacing text
How to:
var greetings = "Hello, old friend!"
// Simple replace
greetings = greetings.replacingOccurrences(of: "old", with: "new")
print(greetings) // "Hello, new friend!"
// Using options for case-insensitive replace
let caseInsensitiveResult = greetings.replacingOccurrences(
of: "hello",
with: "Hi",
options: .caseInsensitive
)
print(caseInsensitiveResult) // "Hi, new friend!"
// Replacing with regular expressions
let regexResult = greetings.replacingOccurrences(
of: "\\bnew\\b",
with: "best",
options: .regularExpression
)
print(regexResult) // "Hello, best friend!"
Deep Dive
We’ve been swapping text in strings since the early days of computing. Initially, it was with simple command-line tools like sed
. In Swift, replacingOccurrences(of:with:)
does the heavy lifting, and you get more control with options like .caseInsensitive
or .regularExpression
.
Alternatives in Swift include using NSRegularExpression
for complex patterns and NSMutableString
for mutable string operations. Under the hood, Swift’s string replacement methods bridge to powerful Objective-C counterparts, providing speed and versatility.