Filter non-digits from string

后端 未结 12 1158
日久生厌
日久生厌 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:18

    You'll want to use NSCharacterSet:

    Check out this NSHipster link for Swift and Obj-C implementations: http://nshipster.com/nscharacterset/

    Similar example:

    var string = "  Lorem    ipsum dolar   sit  amet. "
    
    let components = string.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).filter({!isEmpty($0)})
    
    string = join(" ", components)
    

    See: punctuationCharacterSet

    Description:

    Returns a character set containing the characters in the category of Punctuation. Informally, this set is the set of all non-whitespace characters used to separate linguistic units in scripts, such as periods, dashes, parentheses, and so on.

    @Tapani Makes a great suggestion: NSCharacterSet.decimalDigitCharacterSet().invertedSet

提交回复
热议问题