How to Remove Numbers from a String in Swift

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

Try this code

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

How to remove numbers from a String in Swift

You can do it with the NSCharacterSet

var str = "75003 Paris, France"

var stringWithoutDigit = (str.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet()) as NSArray).componentsJoinedByString("")

println(stringWithoutDigit)

Output :

Paris, France

Taken reference from : https://stackoverflow.com/a/1426819/3202193

Swift 4.x:

let str = "75003 Paris, France"

let stringWithoutDigit = (str.components(separatedBy: CharacterSet.decimalDigits)).joined(separator: "")

print(stringWithoutDigit)

Removing only numbers at beginning of sentences in string - Swift

You can enumerate the sentences, use regular expression to trim leading numbers, and build final string.

E.g.

let string = """
1There were 101 dalmatians in the room. 2 They had 2 parents.
3 The parents were named Pongo and Perdita.
"""

var result: String = ""
string.enumerateSubstrings(in: string.startIndex..., options: .bySentences) { substring, _, _, _ in
guard
let trimmed = substring?.replacingOccurrences(of: #"^\d+\s*"#, with: "", options: .regularExpression)
else { return }
result.append(trimmed)
}
print(result)

There were 101 dalmatians in the room. They had 2 parents.

The parents were named Pongo and Perdita.

There are lots of permutations on the regex pattern. E.g. if you used #"^\d+\.?\)?\s*"#, it would also handle cases like “1. This is a test!” or “1) This is a test.” It just depends upon what variations you want to handle. But if you're just looking for digits only, with or without spaces, then #"^\d+\s*"# should be fine.

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

Remove trailing numbers from String

You can use NumberFormater and set minimum and maximum fraction digits:

let double1 = 1.12
let double2 = 0.00007067999999

let numberFormatter = NumberFormatter()
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 8
numberFormatter.minimumIntegerDigits = 1
numberFormatter.string(for: double1) ?? "" // "1.12"
numberFormatter.string(for: double2) ?? "" // "0.00007068"

if you would like to round the fraction digits down you can set the formatter rounding mode option to .down:

numberFormatter.roundingMode = .down
numberFormatter.string(for: double2) ?? "" // "0.00007067"

How to remove few numbers from telephone number string - Swift


let number = "0044 123 456-7890"
let numberArray = map(number) { String($0) }
let numbersOnly = numberArray.filter { $0.toInt() != nil }
let numbers = "".join(numbersOnly.reverse()[0...9].reverse())
println(numbers) // Prints "1234567890"

This is just to give you a general example of how it can be done. I really don't like using fixed numbers for indexes. This should be safe if your phone numbers always have at least 10 numbers.


Updated the answer for Swift 4.

It's safe and crash friendly now!

let number = "0044 123 456-7890"
let numberArray = number.map { String ($0) }
var numbersOnly = numberArray.filter { Int($0) != nil }
let remove = numbersOnly.count > 3 ? numbersOnly[...3].joined() == "0044" : false
let result = numbersOnly[(remove ? 4 : 0)...]

print(result) // 1234567890

I want to delete last integers value swift

Search backwards for the first non-digit character and drop the trailing digits

let string = "kjgd5676idbh123456"
let result : String
if let range = string.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted, options: .backwards) {
result = String(string[..<range.upperBound])
} else {
result = Int(string) == nil ? string : ""
}

How to remove specific characters or words from a string in swift?

I think this will be faster with a regex solution:

//use NSMutableString so the regex.replaceMatches later will work
var myString:NSMutableString = "43321 This is example hahaha 4356-13"

//add more words to match by using | operator e.g. "[0-9]{1,}|apple|orange"
//[0-9]{1,} simply removes all numbers but is more efficient than [0-9]
let regexPattern = "[0-9]{1,}|apple"

//caseInsensitive or the regex will be much longer
let regex = try NSRegularExpression(pattern: regexPattern, options: .caseInsensitive)

var matches = regex.matches(in: myString as String, options: .withoutAnchoringBounds, range: range)
regex.replaceMatches(in: myString, options: .withoutAnchoringBounds, range: range, withTemplate: "")

print(myString) // This is example hahaha -

Subsequent Strings

var testString3: NSMutableString = "apple banana horse"
matches = regex.matches(in: testString3 as String, options: .withoutAnchoringBounds, range: range)
regex.replaceMatches(in: testString3, options: .withoutAnchoringBounds, range: range, withTemplate: "")
print(testString3) // banana horse


Related Topics



Leave a reply



Submit