如何从字符串中过滤非数字

时间:2017-06-02 18:28:44

标签: swift

我的电话号码是+7(777)777-7777。 我只需要数字和加号:+77777777777来拨打电话。

这只返回数字:

let stringArray = origString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let newString = NSArray(array: stringArray).componentsJoinedByString("")

2 个答案:

答案 0 :(得分:3)

执行此操作的众多方法之一:

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

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

或使用正则表达式:

// 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
)

或者,如果您真的想要使用带有字符集的原始解决方案。

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

答案 1 :(得分:2)

符合部分解决方案的精神,

let origString:NSString = "+7 (777) 777-7777"
let cs = NSCharacterSet(charactersIn: "0123456789+")
let final = origString.components(separatedBy: cs.inverted).joined()