正则表达式无法在iOS中使用$ character

时间:2015-02-02 07:31:56

标签: ios regex nsregularexpression

我是iOS中的RegularExpressions新手。我在我的代码的某些部分使用正则表达式但它不起作用。如果我做错了,请纠正我

我正在调用compareStringWithRegex函数,就像这样

[self compareStringWithRegex:@"Web" withRegexPattern@"eb$"];

方法

- (BOOL)compareStringWithRegex:(NSString *)string
              withRegexPattern:(NSString *)expression {
  @try {

    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression
        regularExpressionWithPattern:expression
                             options:NSRegularExpressionCaseInsensitive
                               error:&error];

    NSTextCheckingResult *match =
        [regex firstMatchInString:string
                          options:0
                            range:NSMakeRange(0, [string length] - 1)];

    if (match) {
      return YES;
    } else {
      return NO;
    }
  }
  @catch (NSException *exception) {

    // NSLog(@"the exception in checking regex is %@",[exception description]);
  }
}

但它不匹配

1 个答案:

答案 0 :(得分:1)

我修改了一点代码。我想这会对你有所帮助,希望这就是你所需要的

- (BOOL)compareStringWithRegex:(NSString *)string
          withRegexPattern:(NSString *)expression {
@try {

    NSError *error = NULL;

    NSRegularExpression *regex = [NSRegularExpression
                                  regularExpressionWithPattern:expression
                                  options:NSRegularExpressionCaseInsensitive
                                  error:&error];

    NSTextCheckingResult *match = [regex firstMatchInString:string
                                                    options:0 range:NSMakeRange(0, [string length])];

    if (match) {
        return YES;
    } else {
        return NO;
    }
}
@catch (NSException *exception) {

    // NSLog(@"the exception in checking regex is %@",[exception description]);
}
}