Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 replacingOccurrences regex

Tags:

regex

swift

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.

like image 524
Denis Avatar asked Apr 23 '17 20:04

Denis


2 Answers

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)
like image 178
vadian Avatar answered Nov 06 '22 17:11

vadian


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: " ")
like image 31
Sweeper Avatar answered Nov 06 '22 17:11

Sweeper