【发布时间】:2016-11-03 20:56:20
【问题描述】:
如果给定句子中包含数组中的任何字符串,我正在尝试在嵌套数组中查找匹配项。
这是我的数组
NSArray *menuItems = @[
@[@"beverage", @"drink", @"smoothie", @"coffee", @"juice", @"shakes", @"tea", @"beer"],
@[@"breakfast", @"egg", @"omelet", @"bagel", @"yogurt", @"pancake", @"cereal", @"waffle", @"oatmeal", @"parfait", @"yoghurt", @"huevos", @"bacon", @"french toast", @"frittata", @"hash brown", @"muesli", @"quiche"],
@[@"omelet", @"brunch", @"pancake", @"waffle", @"huevos", @"bacon", @"blintz", @"sausage", @"casserole", @"crepe", @"egg", @"french toast", @"bacon", @"french toast", @"frittata", @"hash brown", @"muesli", @"quiche", @"salad", @"salmmon", @"soup", @"tartine"],
@[@"dessert", @"sweet", @"waffle", @"cake"],
@[@"appetizer", @"soup", @"side", @"fruit", @"starter", @"snack", @"bread", @"spread"],
@[@"coffee", @"drink", @"beverage", @"espresso", @"cappuccino", @"americano", @"latte", @"macchiato", @"frappuccino", @"flat white"]
];
现在,当我搜索给定的句子时,我想将该数组中的任何字符串与句子中匹配左侧的任何单词进行匹配。 所以如果我有一个像“Hot bagels with cheese”这样的句子,它应该匹配第二个数组中包含的字符串“bagel”。
我的方法是这样的:
NSString *dishName = [NSString stringWithFormat:@"\\b%@\\w*",@"sentence goes here"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF IN %@", dishName];
NSArray *matchedArray = [menuItems filteredArrayUsingPredicate:predicate];
if (matchedArray.count>0) {
NSLog(@"found match for dish name:%@",@"sentence");
}
else {
NSLog(@"Didn't match dish name:%@",@"sentence");
}
现在奇怪了。 根据正则表达式,我在左侧匹配一个单词边界,所以它不应该从左侧进行通配符匹配。
但是当我的句子例如:@“Grilled Tuna Steak Burrito (1 Piece)” 它匹配单词“Steak”的第一个数组中的“tea”字符串。
知道为什么会这样吗?
【问题讨论】:
-
我不想为此使用块谓词。反正发现我的错了,看我的回答
标签: objective-c regex nspredicate