【问题标题】:NSPredicate and simple Regular Expression problemNSPredicate 和简单的正则表达式问题
【发布时间】:2009-10-17 17:17:03
【问题描述】:

我在使用简单的 NSPredicates 和正则表达式时遇到问题:

NSString *mystring = @"file://questions/123456789/desc-text-here";
NSString *regex = @"file://questions+";

NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL isMatch = [regextest evaluateWithObject:mystring];

在上面的示例中,isMatch 始终为 false/NO。

我错过了什么?我似乎找不到匹配 file://questions 的正则表达式。

【问题讨论】:

    标签: objective-c regex cocoa nspredicate


    【解决方案1】:

    NSPredicates 似乎尝试匹配整个字符串,而不仅仅是一个子字符串。您的尾随 + 仅表示匹配一个或多个 's' 字符。您需要允许匹配任何尾随字符。这有效:regex = @"file://questions.*"

    【讨论】:

      【解决方案2】:

      如果你只是想测试字符串是否存在:试试这个

      NSString *myString = @"file://questions/123456789/desc-text-here";
      NSString *searchString = @"file://questions";
      
      NSRange resultRange = [myString rangeWithString:searchString];
      BOOL result = resultRange.location != NSNotFound;
      

      交替,使用谓词

      NSString *myString = @"file://questions/123456789/desc-text-here";
      NSString *searchString = @"file://questions";
      
      NSPredicate *testPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH %@", searchString];
      
      BOOL result = [testPredicate evaluateWithObject:myString];
      

      我相信文档指出使用谓词是检查子字符串是否存在的方法。

      【讨论】:

      猜你喜欢
      • 2012-01-10
      • 2011-05-13
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-29
      相关资源
      最近更新 更多