正则表达式无法识别撇号(')

时间:2018-03-29 18:35:11

标签: objective-c regex nspredicate

我想要一个可以包含

的名字的正则表达式

1)的字母 2)空间 3)撇号

Exp:Raja,Raja reddy,Raja's,

我使用了这个^([a-z]+[,.]?[ ]?|[a-z]+[']?)+$,但它无法识别Apostrophes(')。

- (BOOL)validateFirstNameOrLastNameOrCity:(NSString *) inputCanditate {
    NSString *firstNameRegex =  @"^([a-z]+[,.]?[ ]?|[a-z]+[']?)+$";
    NSPredicate *firstNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@",firstNameRegex];
    return [firstNamePredicate evaluateWithObject:inputCanditate];
}

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找像this这样的模式:^[a-zA-Z ']+$

然而,这非常糟糕。那么变音符号,重音符号和其他许多不属于ASCII字母表的字母呢?

更好的解决方案是允许任何语言的任何类型的信件。 为此,您可以使用Unicode“字母”类别\p{L},例如^[\p{L}]+$。 ..或者你可以放弃这条规则 - 正如合理建议的那样。

答案 1 :(得分:1)

我可以推荐^ [A-Z] [a-zA-Z'] *?

// The NSRegularExpression class is currently only available in the Foundation framework of iOS 4
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[A-Z][a-zA-Z ']*" options:NSRegularExpressionAnchorsMatchLines error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:searchText options:0 range:NSMakeRange(0, [string length])];
return numberOfMatches > 1;

^ [A-Z]:强制从A到Z的大写字母开始

[a-zA-Z'] *:其后是任何数量的特征,即' a'到''' A'到' Z',空格或简单的引用

相关问题