How to remove all letters from an alphanumeric string in Swift

3 Answers

0 votes
/// Removes all alphabetic characters (letters) from a given string,
/// leaving numbers, symbols, and whitespace intact.
///
/// This approach uses `Character.isLetter`, which provides full Unicode support
/// (handling accented characters, Cyrillic, etc., out of the box).
///
/// - Parameter input: The alphanumeric string to process.
/// - Returns: A new `String` with all letters removed.
func removeLetters(from input: String) -> String {
    // filter keeps only the characters where isLetter is false
    return input.filter { !$0.isLetter }
}

// --- Example Usage ---
let mixedString = "abc123XYZ456programming789"
let result = removeLetters(from: mixedString)
print(result) 


/*
run:

123456789

*/

 



answered 5 hours ago by avibootz
0 votes
func removeLettersRegex(from input: String) -> String {
    // \p{L} matches any kind of letter from any language
    return input.replacing(try! Regex(#"\p{L}"#), with: "")
}

// --- Example Usage ---
let mixedString = "abc123XYZ456programming789"
let result = removeLettersRegex(from: mixedString)
print(result) 


/*
run:

123456789

*/

 



answered 5 hours ago by avibootz
0 votes
var mutableString = "abc123XYZ456programming789"

mutableString.removeAll(where: { $0.isLetter })

print(mutableString) 


/*
run:

123456789

*/

 



answered 5 hours ago by avibootz
...