仅将String(IOS)的数量粘贴(Insert)到Label(IOS)中

时间:2017-08-28 13:44:23

标签: ios regex swift copy-paste

我有代码来实现“粘贴”功能。

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

如何制作它以便我只能插入数字???

创建扩展程序文件:

Swift extension example

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 ""
    }

}

1 个答案:

答案 0 :(得分:0)

将此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")

        })
    )