How to remove all chars except those in CharacterSet in Swift

Add the method removingCharacters(in:) to Swift's String type. It returns a new string made by removing the characters in a given character set from the String.

For example:

let string = "+1-202-555-0141"
let set = CharacterSet(charactersIn: "+*#0123456789")
let sanitized = string.removingCharacters(in: set.inverted)
// sanitized is equal to "+12025550141"

Helpers.swift

extension String {
  public func removingCharacters(in set: CharacterSet) -> String {
    let filtered = unicodeScalars.filter { !set.contains($0) }
    return String(String.UnicodeScalarView(filtered))
  }
}

HelpersTests.swift

import XCTest

class HelpersTests: XCTestCase {
  func testRemovingCharacters() {
    let inputText1 = ""
    let set1 = CharacterSet.decimalDigits.inverted
    let sanitized1 = inputText1.removingCharacters(in: set1)
    XCTAssertEqual("", sanitized1)

    let inputText2 = " tab:\tspace: no-break_space: "
    let set2 = CharacterSet.whitespaces
    let sanitized2 = inputText2.removingCharacters(in: set2)
    XCTAssertEqual("tab:space:no-break_space:", sanitized2)

    let inputText3 = " aBc!@#12 $%^&*()-_=+[{]}\\|;:'\"3,<.>/?`~ "
    let set3 = CharacterSet.alphanumerics.inverted
    let sanitized3 = inputText3.removingCharacters(in: set3)
    XCTAssertEqual("aBc123", sanitized3)
  }
}

See also: Convert Array of UnicodeScalar into String in Swift


func trimmedNumber(s : String) -> String {
  let characterSet = Set("+*#0123456789".characters)
  return String(s.characters.lazy.filter(characterSet.contains))
}

Or in Swift 1:

func trimmedNumber(s : String) -> String {
  let characterSet = Set("+*#0123456789")
  return String(lazy(s).filter { characterSet.contains($0) })
}

Swift 3/4:

let set = CharacterSet(charactersIn: "+*#0123456789")
let stripped = s.components(separatedBy: set.inverted).joined()

Tags:

Ios

Swift