正则表达式在带有 $ 字符的 iOS 中不起作用

Regular Expression not working in iOS with $ character

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

我这样调用 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]);
  }
}

但是不匹配

我稍微修改了代码。我认为这会对您有所帮助,希望这就是您所需要的

- (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]);
}
}