ios - 如何在iOS sdk中使用正则表达式

标签 ios iphone objective-c regex

如何在iOS sdk中使用正则表达式?

我需要使用正则表达式验证 UITextField 只允许将数值输入 UITextField

最佳答案

在你的 shouldChangeCharactersInRange 中你可以这样做

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

        NSString *expression = @"^([0-9]+$";

        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression 
                                                                               options:NSRegularExpressionCaseInsensitive 
                                                                                error:nil];
        NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
                                                            options:0
                                                              range:NSMakeRange(0, [newString length])];        
        if (numberOfMatches == 0)
            return NO;        


    return YES;
}

关于ios - 如何在iOS sdk中使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11206144/

相关文章:

ios - 使用 Storyboard的 iPhone X 中的底部边距

iphone - 如何让iPhone中的两个导航栏重叠?

ios - 应用内购买管理中不显示消耗品、非消耗品、订阅

ios - AFNetworking 架构 i386 的 undefined symbol : "_OBJC_CLASS_$_AFHTTPSessionManager"

iphone - 如何解决这个问题签名无效,或者不是用Apple提交证书签名的。 (-19011)

iOS:具有动态单元格高度的 UITableViewCell 内的 UITableView

iphone - 数字布局在安全的 UITextField 中不粘?

ios - 新初始化和数组初始化之间的区别

c++ - 从后台线程错误修改自动布局引擎,来自 C++

ios - 使用 IOS 设备的蓝牙连接