Skip to content

Instantly share code, notes, and snippets.

@alexbaramilis
Last active April 16, 2019 15:55
Show Gist options
  • Save alexbaramilis/3e2fc9638a0c8b44eeca8739ac0134e9 to your computer and use it in GitHub Desktop.
Save alexbaramilis/3e2fc9638a0c8b44eeca8739ac0134e9 to your computer and use it in GitHub Desktop.
Swift String Extension for finding the indices of all the numbers in a string.
import Foundation
extension String {
/// Returns the indices of all the numbers in the string.
///
/// If a number is directly preceded by a dot/comma, the index of the dot/comma
/// will also be returned.
/// This accounts for potential numbers with decimal or thousands separators.
var indicesOfNumbers: [Int] {
var indices = [Int]()
var searchStartIndex = self.startIndex
while searchStartIndex < self.endIndex,
let range = self.rangeOfCharacter(from: CharacterSet.decimalDigits,
range: searchStartIndex..<self.endIndex),
!range.isEmpty
{
let index = distance(from: self.startIndex, to: range.lowerBound)
if index > 0 {
let previousIndex = self.index(self.startIndex, offsetBy: index - 1)
if let previousCharacter = self[previousIndex].unicodeScalars.first,
(previousCharacter == "." || previousCharacter == ",")
{
indices.append(index - 1)
}
}
indices.append(index)
searchStartIndex = range.upperBound
}
return indices
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment