2

I'm trying to convert the parts of code that Xcode couldn't convert to Swift3

In swift 2.3 to replace multiple characters in a string I used :

var phone = "+ 1 (408)-456-1234"
phone = phone.replaceCharacters("  ) ( -   ‑", toSeparator: "")

this should give +14084561234

In swift 3 I'm using this :

phone = phone.replacingOccurrences(of: " |(|)|-", with: "z",options: .regularExpression)

this code gives +1(408)4561234

How to replace multiple characters in a string (Swift3)?

but this is not working correctly ? any ideas

2
  • Could you please describe what exactly you want to do? It's obvious your Swift 3 code doesn't contain a valid regular expression. Commented Jan 8, 2017 at 16:54
  • I think it's clear. post updated Commented Jan 8, 2017 at 17:01

3 Answers 3

16

You have to fix the regular expression to create a set of characters you want to remove, e.g.:

var phone = "+ 1 (408)-456-1234"
phone = phone.replacingOccurrences(of: "[ |()-]", with: "", options: [.regularExpression])
print(phone) // +14084561234

but a better solution is to create a set of characters you want to keep and remove all the others:

phone = phone.replacingOccurrences(of: "[^\\d+]", with: "", options: [.regularExpression])
Sign up to request clarification or add additional context in comments.

Comments

5

Brackets in regular expressions means group. By other words they have to be escaped:

var phone = "+ 1 (408)-456-1234" 
phone = phone.replacingOccurrences(of: " |\\(|\\)|-", with: "",options: .regularExpression)
// "+14084561234"

But it can be simplified by enumeration of characters:

var phone = "+ 1 (408)-456-1234" 
phone = phone.replacingOccurrences(of: "[-() ]", with: "",options: .regularExpression)
// "+14084561234"

Comments

0

Swift 5

var phone = "+ 1 (408)-456-1234"
let characterSet = CharacterSet(charactersIn: " )(-‑")
phone = phone.components(separatedBy: characterSet).joined(separator: "")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.