Swift
String Manipulation
Programming
Code Example
Text Processing

Remove all non-numeric characters from a string in swift

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Removing all non-numeric characters from a Swift string is usually a matter of deciding what you mean by numeric. If you want only ASCII digits such as 0 through 9, a simple filter is often the clearest option. If you want broader Unicode decimal digit support, CharacterSet.decimalDigits is the safer choice.

Simple filter Approach

For many app-level tasks such as cleaning a phone number or extracting digits from an identifier, this is enough:

swift
let input = "Order #A-1029"
let digitsOnly = input.filter { $0.isNumber }
print(digitsOnly)

This keeps characters that Swift considers numeric and removes everything else. It is concise, readable, and usually the best first answer.

Restricting to ASCII Digits

Sometimes you explicitly want only 0 through 9. In that case, check the character range directly.

swift
let input = "+1 (555) 123-4567"
let digitsOnly = String(input.filter { $0 >= "0" && $0 <= "9" })
print(digitsOnly)

This is useful when the downstream system expects a plain digit string with no other numeric characters.

Using CharacterSet.decimalDigits

If you want to work at the Unicode-scalar level, CharacterSet.decimalDigits is another solid option.

swift
1import Foundation
2
3let input = "Invoice 2025-09-23"
4let digits = input.unicodeScalars.filter {
5    CharacterSet.decimalDigits.contains($0)
6}
7let result = String(String.UnicodeScalarView(digits))
8print(result)

This version is slightly more verbose, but it makes the numeric rule explicit and works well when you are already manipulating Unicode scalars.

Regular Expressions When the Pattern Is Broader

A regular expression can also remove non-digits, though it is often more machinery than the problem needs.

swift
1import Foundation
2
3let input = "Code: AB-123-CD"
4let result = input.replacingOccurrences(
5    of: "[^0-9]",
6    with: "",
7    options: .regularExpression
8)
9print(result)

Regex becomes more attractive when the string-cleaning logic is part of a larger text-normalization pipeline rather than a one-off digit filter.

Which Version Should You Use

A practical rule is:

  • use filter with isNumber for concise general-purpose code
  • use an ASCII range if the result must be strictly 0 through 9
  • use regex when the broader text-cleaning logic already depends on regular expressions

That keeps the code aligned with the real input requirement instead of forcing every case through the same tool.

Return Type Considerations

filter on String returns a String, so in the simplest examples you may not need an extra conversion. But when you operate on Unicode scalars or other intermediate views, you often rebuild the final string explicitly. It is worth checking the exact type you are producing, especially when the cleaned digits are passed into validation or formatting code afterward.

Common Pitfalls

  • Using isNumber when you really need only ASCII digits can admit characters you did not intend to keep. Use the explicit "0"..."9" check when the output format is strict.
  • Reaching for regex first can make a simple digit filter harder to read than necessary. filter is usually the clearest default in Swift.
  • Treating phone-number cleanup and numeric parsing as the same task causes validation mistakes. Removing non-digits is only the cleanup step, not the full business rule.
  • Forgetting about Unicode behavior can create surprises if your input is not plain ASCII text. Decide whether international numeric characters should count.
  • Assuming the cleaned string is automatically valid for conversion to Int can fail on empty input or large values. Validate the result before numeric parsing.

Summary

  • In Swift, filter is usually the simplest way to remove non-numeric characters.
  • Use isNumber for broad numeric filtering or an explicit range for ASCII digits only.
  • 'CharacterSet.decimalDigits is useful when working with Unicode scalars.'
  • Regular expressions work, but they are often heavier than necessary for this task.
  • Choose the approach based on whether your definition of numeric is broad or strictly digit-only.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.