Filter non-digits from string

后端 未结 12 1128
日久生厌
日久生厌 2020-12-01 11:36

Using only swift code I cant figure out how to take \"(555) 555-5555\" and return only the numeric values and get \"5555555555\". I need to remove all the parentheses, whit

12条回答
  •  悲&欢浪女
    2020-12-01 12:34

    Here is @Tapani's Swift 2.0 answer as a handy String extension, (length property is not part of solution but I left it in example because it is also handy):

    import Foundation
    
    extension String {
    
        var length : Int {
            return self.characters.count
        }
    
        func digitsOnly() -> String{
            let stringArray = self.componentsSeparatedByCharactersInSet(
                NSCharacterSet.decimalDigitCharacterSet().invertedSet)
            let newString = stringArray.joinWithSeparator("")
    
            return newString
        }
    
    }
    

    Usage:

    let phone = "(123)-123 - 1234"
    print(phone.digitsOnly())
    

提交回复
热议问题