Replacing Elements in a String
Table of Contents
One of the most common problems we face when working with strings is modifying certain characters in the string.
This problem can be easily solved with the use of regular expressions (regex).
Before Swift 5.7#
If you can’t uae the newest Swift you can achieve this by using the method replacingOccurrences(of:with:options)
.
Here is an example of its use:
let s = "12abc34"
let t = ss.replacingOccurrences(
of: "[a-z]", // regex
with: "",
options: .regularExpression
)
// output: "1234"
If we want to do the opposite (i.e., to keep everything but lowercase letters), we can use the symbol ^
to invert the expression set.
let s = "12abc34"
let t = ss.replacingOccurrences(
of: "[^a-z]", // regex
with: "",
options: .regularExpression
)
// output: "abc"
After Swift 5.7#
If we have access to a newer version of swift, you can use a simpler method to achieve the same result: replacing(_:with:maxReplacements:)
.
let s = "12abc34"
let t = s.replacing(/[a-z]/, with: "")
// output: "1234"
As before, we can use ^
to obtain the inverse result:
let s = "12abc34"
let t = s.replacing(/[^a-z]/, with: "")
// output: "abc"
Conclusion#
Regular expressions are quite powerful and can help us to solve problems with a simple predicate that describes what the want to obtain.
Regex may seems hard to grasp at first, but we can start with little examples like these to gain experience with this useful tool.