我需要正则表达式公式 例如“17% 折扣等等” 或“2% 折扣等等等等” 因此,如果字符串以一位或两位数字开头,后跟百分号、空格和单词“off”
我试过了
NSPredicate* test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^[0-9]{1,2}% off"];
if ( [test evaluateWithObject:candidate] )
{
.... etc..
但运气不好。
我很欣赏任何见解。
最佳答案
使用这个命令行示例应用程序,它可以正常工作。
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSArray *lines = @[ @"17% off etc.", @"2% off", @"off by 12%" ];
NSPredicate* test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^[0-9]{1,2}% off.*"];
[lines enumerateObjectsUsingBlock:^(NSString *candidate, NSUInteger idx, BOOL *stop) {
if ( [test evaluateWithObject:candidate] ){
NSLog(@":)");
} else{
NSLog(@":(");
}
}];
}
return 0;
}
输出:
2012-08-08 15:46:16.213 regextest[1305:303] :)
2012-08-08 15:46:16.215 regextest[1305:303] :)
2012-08-08 15:46:16.215 regextest[1305:303] :(
<小时/>
如果该行包含更多字符,它应该看起来像
NSPredicate* test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^[0-9]{1,2}% off.*"];
.*
表示可能存在任意数量的任意字符。
关于objective-c - Objective C 正则表达式以 1 或 2 位数字开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11865650/