NSPredicates 开始于

发布于 2024-10-05 02:52:33 字数 392 浏览 5 评论 0原文

我有一个 NSArray,其内容是格式类似于以下内容的字符串: [Az]{+}-[0-9]{+}

所以基本上是一堆重复的字母字符、分隔符,然后是 1 个或多个数字,所以

我想按数组中与分隔符匹配的值进行过滤,但是我似乎无法以预测器的格式明确指定它:

NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH %@", aValue];
NSArray *filtered = [entries filteredArrayUsingPredicate:aPredicate];

How do you constrain thefilter for such a case?

I have an NSArray whose contents are strings with a format similar to:
[A-z]{+}-[0-9]{+}

so basically a bunch of repeating alpha characters, a separator, and then 1 or more digits so

I want to filter by values in the array that match up to the separator but I can't seem to explicitly specify it in my predicator's format:

NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH %@", aValue];
NSArray *filtered = [entries filteredArrayUsingPredicate:aPredicate];

How do you constrain the filtering for such a case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

·深蓝 2024-10-12 02:52:33

您可以使用“MATCHES”运算符进行正则表达式搜索,如下所示:

NSPredicate * p = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"[a-z]+-.*"];
NSArray * s = [NSArray arrayWithObject:@"abc-123"];
NSLog(@"%@", [s filteredArrayUsingPredicate:p]);

不过,有一个警告。正则表达式在整个字符串中进行匹配。因此,如果您想查找以 3 个字母开头的所有元素,您的表达式不能只是“[az]{3}”。它必须是“[az]{3}.*”。第一个将匹配任何不是 3 个字母的内容,而第二个将匹配任何长度至少为 3 个字母的内容。

我花了一段时间才意识到这一点......

You could use the "MATCHES" operator to do a regular expression search, like so:

NSPredicate * p = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"[a-z]+-.*"];
NSArray * s = [NSArray arrayWithObject:@"abc-123"];
NSLog(@"%@", [s filteredArrayUsingPredicate:p]);

There is a caveat, though. The regular expression is matched across the entire string. So if you want to find all the elements that begin with 3 letters, your expression can't just be "[a-z]{3}". It has to be "[a-z]{3}.*". The first will fail for anything that's not 3 letters, whereas the second will match anything that's at least 3 letters long.

Took me a while to realize this...

蓝天 2024-10-12 02:52:33

您可能想要使用 MATCHES 运算符来使用正则表达式。

请参阅 谓词编程指南:正则表达式

You probably want to use the MATCHES operator that lets you use Regular Expressions.

See Predicate Programming Guide:Regular Expressions

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文