仅将字符串的数字粘贴(插入)到标签(IOS)中

Paste (Insert) into Label (IOS) only the numbers of String

我有实现 "Paste" 功能的代码。

但是插入了所有符号,而不仅仅是数字。

如何才能只插入数字???

创建扩展文件:

Past (Photo)

更新代码

actionSheetController.addAction(
        UIAlertAction(title: NSLocalizedString("Past", comment: ""), style: .default, handler: { [weak self] _ in
            guard let strongSelf = self else { return }

            strongSelf.displayResultLabel.text = UIPasteboard.general.string.onlyNumbers()

            print ("Past")

        })
    )



extension String {

    func onlyNumbers() ->String{
        do{
            let regex = try NSRegularExpression(pattern: "([//.,\d])*", options:[.dotMatchesLineSeparators])
            var result : String = ""

            for resultMatch in regex.matches(in: self, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSMakeRange(0, NSString(string: self).length)) {
                result += NSString(string: self).substring(with: resultMatch.range)
            }
            return result
        }
        catch
        {

        }

        return ""
    }

}

将此 extensionregex 函数结合使用,仅获取您的 String

的号码
    extension String {

    func onlyNumbers() ->String{
        do{
            let regex = try NSRegularExpression(pattern: "([//.,\d])*", options:[.dotMatchesLineSeparators])
            var result : String = ""

            for resultMatch in regex.matches(in: self, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSMakeRange(0, NSString(string: self).length)) {
                result += NSString(string: self).substring(with: resultMatch.range)
            }
            return result
        }
        catch
        {

        }

        return ""
    }

}

你可以这样使用它

actionSheetController.addAction(
        UIAlertAction(title: NSLocalizedString("Past", comment: ""), style: .default, handler: { [weak self] _ in
            guard let strongSelf = self else { return }

            strongSelf.displayResultLabel.text = UIPasteboard.general.string.onlyNumbers()
            print ("Past")

        })
    )