我有代码来实现“粘贴”功能。
但是插入所有符号而不仅仅是数字。
如何制作它以便我只能插入数字???
创建扩展程序文件:
更新了代码
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 ""
}
}
答案 0 :(得分:0)
将此extension
与regex
功能一起使用,只能获取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")
})
)