1

I have code to implement the "Paste" function.

But there is an insertion of all symbols and not only numbers.

How can I make it so that I can insert only numbers ???

Creating an Extension file:

Swift extension example

Past (Photo)

Updated code

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

}
BLC
  • 97
  • 7
  • Convert the string to a number and back OR use NSCharacterSet and extract the numbers from the string. – Brandon Aug 28 '17 at 13:50

1 Answers1

0

Use this extension with regex function to get only the numbers of your 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 ""
    }

}

you can use it like this

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

        })
    )
Reinier Melian
  • 20,519
  • 3
  • 38
  • 55