Skip to content
DeveloperMemos

Filtering Non-Digit Characters from Strings in Swift

Swift, iOS, String Manipulation1 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.

Using Character Sets

Swift's CharacterSet class provides a convenient way to filter characters.

Example

1extension String {
2 func removingNonNumericCharacters() -> String {
3 let digits = CharacterSet.decimalDigits
4 return self.filter { char in
5 char.unicodeScalars.contains(where: digits.contains)
6 }
7 }
8}
9
10let phone = "(555) 555-5555"
11let filteredPhone = phone.removingNonNumericCharacters()
12print(filteredPhone) // "5555555555"

String Extension for Reusability

Creating a string extension can make the functionality reusable across the application.

Example

1extension String {
2 var digitsOnly: String {
3 let nonDigits = CharacterSet.decimalDigits.inverted
4 return self.components(separatedBy: nonDigits).joined()
5 }
6}
7
8let rawInput = "(555) 555-5555"
9let cleanInput = rawInput.digitsOnly
10print(cleanInput) // "5555555555"