【问题标题】:Filter NSArray of strings when portion of string is empty using NSPredicate当字符串的一部分为空时,使用 NSPredicate 过滤字符串的 NSArray
【发布时间】:2020-04-07 03:29:58
【问题描述】:

我想使用 NSPredicate 过滤掉字符串右侧部分为空的字符串数组中的项目,但我对 NSPredicate 的了解有限。

字符串看起来应该像{"0,General", "1,Sports", "2,Entertainment"} 等。

我想过滤掉你有类似的情况:"0," 甚至","

所以如果我有{"0,General", "1,Sports", "0,","2,Entertainment"},我想过滤掉有缺陷的类别“0”。

我知道我可以使用以下内容过滤掉完全空的字符串:

NSArray *filteredcats = [mycats filteredArrayUsingPredicate:
                         [NSPredicate predicateWithFormat:@"length > 0"]];

如何过滤掉数组中逗号右侧为空的字符串?

【问题讨论】:

  • 只需遍历数组并使用字符串比较运算符进行过滤,并将所需的元素添加到输出数组中。使用谓词不会带来任何性能优势
  • 看起来您没有正确地表示您的数据,并且现在依靠 hacky 方法来管理该数据。我会重新考虑您如何保存数据;例如,通过保留一组自定义类。

标签: ios nsarray nspredicate


【解决方案1】:

您可以轻松地为此使用正则 r 表达式,

NSArray *myArray = @[@",First",@"0,General",@"1,Sports",@"2,Entertainment",@"3,",@","];
NSString *regex = @"^\\d,\\w+$";
NSPredicate *filter = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
NSArray *matches = [myArray filteredArrayUsingPredicate:filter];

NSLog(@"matches: %@", matches);
matches: (
    "0,General",
    "1,Sports",
    "2,Entertainment"
)

【讨论】:

  • 对不起。我的意思是过滤掉逗号两侧没有有效字符串的情况,例如“0”或“,General”,但“0,General”是有效的。有没有办法用正则表达式做到这一点? (我更新了问题以使其更清楚。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多