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

标签 swift

我的电话号码是 +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/

相关文章:

ios - Pan Gesture 不移动个人 View

ios - 将圆角应用于 UIView 时约束无法正确显示(仅适用于 iPhone XS Max 和 + 版本)

swift - 在 swift 中查询 sqlite 数据库的更好方法

swift - SceneKit 相机动画 move 和减速

ios - UIAccessibility - 画外音不适用于 NSMutableAttributedString

ios - 无法在 Storyboard的容器 View 内添加 TextView 名称

objective-c - OSX - 从缩放按钮禁用全屏模式?

ios - 当尝试按下按钮将 Sprite 的 zRotation 增加 1 度时,旋转不正确

使用 Sqlite 和 GRDB 的 SwiftUI FileDocument

SwiftUI:如何使用可变数据在列表中实现 NavigationLinks?