【问题标题】:Regular expressions in Objective-C to search a string starting with #Objective-C 中的正则表达式用于搜索以 # 开头的字符串
【发布时间】:2012-07-03 07:40:13
【问题描述】:

我的代码在下面,但它不起作用。

NSString *regex = @"^#";

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

if ([regextest evaluateWithObject:secondHalfString] == YES) {
    NSLog(@"Match!");
} else {
    NSLog(@"No match!");
}

有什么问题吗?

【问题讨论】:

    标签: objective-c regex cocoa foundation


    【解决方案1】:

    matches 在谓词中适用于整个字符串,因此要获得您所追求的,请像这样编写正则表达式:

    @"^#.*"
    

    【讨论】:

      【解决方案2】:

      注意

      The predicate format string syntax is different from the regular expression syntax.

      on the Predicate documention.

      有关可可的正则表达式,请查看this answer

      【讨论】:

        【解决方案3】:

        如果你正在寻找一个以某个字符串开头的字符串,你应该使用@"SELF BEGINSWITH #"之类的东西,它比使用正则表达式要快得多。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-09-16
          • 2021-06-25
          • 2014-10-28
          • 1970-01-01
          • 2012-08-05
          • 1970-01-01
          • 1970-01-01
          • 2014-09-15
          相关资源
          最近更新 更多