【问题标题】:How to find if the first character of last word in a NSString value is Ampersand using NSRegularExpression?如何使用 NSRegularExpression 查找 NSString 值中最后一个单词的第一个字符是否是 & 符号?
【发布时间】:2012-01-25 11:31:40
【问题描述】:

我想使用 NSRegularExpression 查找 NSString 值中最后一个单词的第一个字母是否以 & 开头。 我使用了以下表达式,但它显示了最后一个单词匹配,即使 & 符号在最后一个单词中的任何位置。 请告诉我我该如何实现它。 谢谢你。

        BOOL flagSymbolFound = NO; 
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[&]\\b\\w*$" options:NSRegularExpressionCaseInsensitive error:&error]; 
if(!error) { 
    NSUInteger numberOfMatches = [regex numberOfMatchesInString:stringValue options:0 range:NSMakeRange(0, [stringValue length])];
          if(numberOfMatches > 0) 
              flagSymbolFound = YES; 
          else 
              flagSymbolFound = NO; 
} 

【问题讨论】:

    标签: iphone objective-c regex nsregularexpression


    【解决方案1】:

    尝试"\\s[&]\\w+$" 模式。它应该匹配以空格分隔的单词,例如foo &bar

    【讨论】:

      【解决方案2】:

      尝试在正则表达式的开头添加“^”锚:

      NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[&]\\b\\w*$" options:NSRegularExpressionCaseInsensitive error:&error]; 
      

      【讨论】:

      • 是的 Ennukiller,它也不适合我。你还有其他建议吗?谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      相关资源
      最近更新 更多