objective-c - Objective C 正则表达式以 1 或 2 位数字开头

标签 objective-c regex cocoa nspredicate

我需要正则表达式公式 例如“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/

相关文章:

cocoa - 是否可以使用 FSEvents 获取文件夹已移动的通知?

cocoa - 设置 Action 名称 : method purpose for NSUndoManager class

objective-c - 比较 Cocoa 中的字符串

javascript - 计算字符串中的所有子串大小写

iphone - 临时显示其他选项卡时 UIRefreshControl 卡住 (iOS 7)

regex - 正则表达式提取嵌套括号内的单词

java - 第二个捕获组不捕获

objective-c - 如何将整数与 Objective-C 枚举进行比较

iphone - 如何在通过 Storyboard 使用静态内容时更改分组 tableView 标题部分中的字体样式

ios - 如何在iTunes Connect中添加多个应用内购买?