从字符串中过滤非数字 [英] Filter non-digits from string

查看:56
本文介绍了从字符串中过滤非数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅使用 swift 代码我无法弄清楚如何取(555)555-5555"并仅返回数值并获得5555555555".我需要删除所有括号、空格和破折号.我能找到的唯一例子是在 Objective-C 中,它们似乎都使用 .trim() 方法.看起来好像 swift 没有这个方法,但它有 .stringByTrimmingCharacters 方法,但这似乎只是修剪数据前后的空格.

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, white spaces, and the dash. The only examples I can find are in objective-C and they seem to all use the .trim() method. It appears as though swift doesn't have this method but it does have the .stringByTrimmingCharacters method, but that only seems to trim the white spaces before and after the data.

推荐答案

Swift 3 &4

extension String {
    var digits: String {
        return components(separatedBy: CharacterSet.decimalDigits.inverted)
            .joined()
    }
}

Swift 5

你应该可以省略return

还有:阅读来自@onmyway133 的评论,请注意

Also: Read the comment from @onmyway133 for a word of caution

这篇关于从字符串中过滤非数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆