gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:56:06 25 4
gpt4 key购买 nike

我的电话号码是 +7 (777) 777-7777。我只需要数字和加号:+77777777777 即可调用电话。

这只返回数字:

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

最佳答案

许多方法之一:

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

关于swift - 如何从字符串中过滤非数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44335323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com