I'm having trouble with my replacingOccurrences function. I have a string like so:
let x = "&john &johnny &johnney"
What I need to do is remove only "&john"
So I have this code:
y = "&john"
x = x.replacingOccurrences(of: y, with: " ", options: NSString.CompareOptions.regularExpression, range: nil)
The problem I get is that this removes All instances of john... And I'm left with:
"ny ney"
Also I thought about setting the range, however, that wont really solve my problem because the names could be in a different order.
First of all your code does not compile because x
must be var
.
To remove only &John
with regular expression you need to check if the end of the query is a word boundary:
var x = "&john &johnny &johnney"
let pattern = "&john\\b"
x = x.replacingOccurrences(of: pattern, with: " ", options: .regularExpression)
Add spaces to the string so that it becomes " &john "
. Now it does not remove unnecessary characters.
However, if &john
is the first or last in the list of names, this will not work. To solve this, you just need to check if the string has a suffix or prefix of &john
by calling hasSuffix
and hasPrefix
.
Actually, I just thought of a better solution:
x = x.components(separatedBy: " ").
filter { $0 != "&john" }.joined(separator: " ")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With