— Swift, iOS, String Manipulation — 1 min read
In Swift, removing non-digit characters from a string is a common task. This article demonstrates several methods to achieve this, including the use of character sets, regular expressions, and string extensions.
Swift's CharacterSet
class provides a convenient way to filter characters.
1extension String {2 func removingNonNumericCharacters() -> String {3 let digits = CharacterSet.decimalDigits4 return self.filter { char in5 char.unicodeScalars.contains(where: digits.contains)6 }7 }8}9
10let phone = "(555) 555-5555"11let filteredPhone = phone.removingNonNumericCharacters()12print(filteredPhone) // "5555555555"
Creating a string extension can make the functionality reusable across the application.
1extension String {2 var digitsOnly: String {3 let nonDigits = CharacterSet.decimalDigits.inverted4 return self.components(separatedBy: nonDigits).joined()5 }6}7
8let rawInput = "(555) 555-5555"9let cleanInput = rawInput.digitsOnly10print(cleanInput) // "5555555555"