简体   繁体   中英

Using NSRegularExpression to validate only String or Number

ok in IPad i have 2 textfield one accepting only string and other textField accepts integer only.

so can i validate them using NSRegularExpression ?

如果您使用的是RegExKit库

[_yourString isMatchedByRegex:@"\\d+"];

You could use NSPredicate to serve your purpose here.

To match numbers:

NSString *number = @"12345";
NSString *regex = @"[0-9]*";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL match = [predicate evaluateWithObject:number]);

To match strings:

NSString *string = @"Hello";
NSString *regex = @"[a-z]*";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES[C] %@", regex];
BOOL match = [predicate evaluateWithObject:string]);

In the above regex @"[az]*"; I've omitted the capitalized characters "AZ" because I've used MATCHES[C] in the predicate in which C stands for the case-insensitivity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM