Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 replacingOccurrences of multiple strings

Tags:

swift

I have JavaScript code that looks like the following:

foo.replace(/(\r\n|\n|\r)/gm, "");

Basically this strips any return carriages and new lines from my string. I'd like to do something similar in Swift 3.

I see func replacingOccurrences(of target: String, with replacement: String, options: CompareOptions = default, range searchRange: Range<Index>? = default) -> String is available. The problem is, this only takes one string in the of parameter.

Does this mean I need to call the method multiple times for each of my instances above, once for \r\n, once for \n\ and once for \r? Is there anyway to potentially accomplish something closer to what the regex is doing instead of calling replacingOccurrences three times?

like image 347
randombits Avatar asked Jan 04 '17 02:01

randombits


2 Answers

Use replacingOccurrences with the option set to regularExpression.

let updated = foo.replacingOccurrences(of: "\r\n|\n|\r", with: "", options: .regularExpression)
like image 138
rmaddy Avatar answered Sep 21 '22 10:09

rmaddy


To replace non-digits you can use "\D" as a regular expression

let numbers = "+1(202)-505-71-17".replacingOccurrences(of: "\\D", with: "", options: .regularExpression)

You can find how to use other regular expressions here

like image 41
KIO Avatar answered Sep 23 '22 10:09

KIO