我有实现“粘贴”功能的代码。
但是插入了所有符号,而不仅仅是数字。
我怎样才能让它只能插入数字???
创建扩展文件:
更新代码
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 ""
}
}
最佳答案
将此扩展
与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")
})
)
关于ios - 仅将字符串的数字粘贴(插入)到标签(IOS)中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45920542/