Remove All Non-Numeric Characters from a String in Swift

Remove all non-numeric characters from a string in swift

I was hoping there would be something like stringFromCharactersInSet() which would allow me to specify only valid characters to keep.

You can either use trimmingCharacters with the inverted character set to remove characters from the start or the end of the string. In Swift 3 and later:

let result = string.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789.").inverted)

Or, if you want to remove non-numeric characters anywhere in the string (not just the start or end), you can filter the characters, e.g. in Swift 4.2.1:

let result = string.filter("0123456789.".contains)

Or, if you want to remove characters from a CharacterSet from anywhere in the string, use:

let result = String(string.unicodeScalars.filter(CharacterSet.whitespaces.inverted.contains))

Or, if you want to only match valid strings of a certain format (e.g. ####.##), you could use regular expression. For example:

if let range = string.range(of: #"\d+(\.\d*)?"#, options: .regularExpression) {
let result = string[range] // or `String(string[range])` if you need `String`
}

The behavior of these different approaches differ slightly so it just depends on precisely what you're trying to do. Include or exclude the decimal point if you want decimal numbers, or just integers. There are lots of ways to accomplish this.


For older, Swift 2 syntax, see previous revision of this answer.

Remove non numeric characters from string having multiple float values using for loop

Split the string using letters as the separator. Remove empty strings from the result. Map the remaining number strings into real numbers.

let string = "12.1gh34.5abc32.1"
let numbers = string.components(separatedBy: .letters)
.filter { !$0.isEmpty }
.compactMap { Double($0) }

The output is:

[12.1, 34.5, 32.1]

If you want to deal with anything that isn't a decimal digit or comma, you can replace .letters with:

CharacterSet(charactersIn: "0123456789.").inverted

How can i remove all the numbers from a string in Swift 3?

Try this code

let string = string.components(separatedBy: CharacterSet.decimalDigits).joined()

Strip Non-Alphanumeric Characters from an NSString

We can do this by splitting and then joining. Requires OS X 10.5+ for the componentsSeparatedByCharactersInSet:

NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
NSString *strippedReplacement = [[someString componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];

Remove all non-numeric characters from an NSString, keeping spaces

Easily done by creating a character set of characters you want to keep and using invertedSet to create an "all others" set. Then split the string into an array separated by any characters in this set and reassemble the string again. Sounds complicated but very simple to implement:

NSCharacterSet *setToRemove =   
[NSCharacterSet characterSetWithCharactersInString:@"0123456789 "];
NSCharacterSet *setToKeep = [setToRemove invertedSet];

NSString *newString =
[[someString componentsSeparatedByCharactersInSet:setToKeep]
componentsJoinedByString:@""];

result: 333 9599 99

Delete non alphabetic characters at the starting of String

I am able to remove leading white spaces using regular expression. This is the code :

extension String {
func trimLeadingWhitespaces() -> String {
return self.replacingOccurrences(of: "^\\s+", with: "", options: .regularExpression)
}
}

let string = " Some string abc"
let trimmed = string.trimLeadingWhitespaces()
print(trimmed)

How to filter non-digits from string

One of the many ways to do that:

let isValidCharacter: (Character) -> Bool = {
($0 >= "0" && $0 <= "9") || $0 == "+"
}

let newString = String(origString.characters.filter(isValidCharacter))

or using a regular expression:

// not a +, not a number
let pattern = "[^+0-9]"

// replace anything that is not a + and not a number with an empty string
let newString = origString.replacingOccurrences(
of: pattern,
with: "",
options: .regularExpression
)

or, if you really want to use your original solution with a character set.

let validCharacters = CharacterSet(charactersIn: "0123456789+")
let newString = origString
.components(separatedBy: validCharacters.inverted)
.joined()

How to remove non numeric characters from phone number in objective-c?

See this answer: https://stackoverflow.com/a/6323208/60488

Basically:

NSString *cleanedString = [[phoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789-+()"] invertedSet]] componentsJoinedByString:@""];

For your case you may want to remove the characters "-", "(" and ")" from the character set.

Swift - Getting only AlphaNumeric Characters from String

You may directly use replacingOccurrences (that removes all non-overlapping matches from the input string) with [^A-Za-z0-9]+ pattern:

let str = "_<$abc$>_"
let pattern = "[^A-Za-z0-9]+"
let result = str.replacingOccurrences(of: pattern, with: "", options: [.regularExpression])
print(result) // => abc

The [^A-Za-z0-9]+ pattern is a negated character class that matches any char but the ones defined in the class, one or more occurrences (due to + quantifier).

See the regex demo.



Related Topics



Leave a reply



Submit