1

我需要 ex“ 17% off etc etc”或“ 2% off etc etc etc”的正则表达式,所以如果字符串以一位或两位数字开头,后跟百分号、空格和单词“off”

我试过

NSPredicate* test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^[0-9]{1,2}% off"];
if ( [test evaluateWithObject:candidate] )
{
.... etc..

但没有运气。

我很欣赏任何见解。

4

1 回答 1

1

使用这个命令行示例应用程序,它工作得很好。

#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.*"];

表示.*可能存在任意数量的任意字符。

于 2012-08-08T13:47:24.683 回答