4

我正在尝试验证 Objective-C 中的名字。请注意,名称可以包含空格且只能包含字母。

这是我的代码不起作用:

NSString *nameRegex = @"^[A-Z][a-z]*[\\s{L}\\s{M}\\s{Nl}][A-Z][a-z]*$";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
BOOL isValid = [nameTest evaluateWithObject:name];
return isValid;
4

6 回答 6

5

我得到了它 :

NSString *nameRegex = @"[a-zA-z]+([ '-][a-zA-Z]+)*$";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
BOOL isValid = [nameTest evaluateWithObject:name];
return isValid;
于 2013-11-12T09:24:45.780 回答
1

这种方法对我有用:

-(BOOL)validate:(NSString *)string
{
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[a-zA-Z ]" options:0 error:&error];    
    NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])];        
    return numberOfMatches == string.length;
}
于 2013-11-12T09:26:51.090 回答
0

我正在使用以下代码

NSString *yourstring = @"hello";

NSString *Regex = @"[a-zA-Z][a-zA-Z ]*";
NSPredicate *TestResult = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex];

if ([TestResult evaluateWithObject:yourstring] == true)
{

    // validation passed
}
else
{
// invalid name
}
于 2015-11-06T10:24:30.043 回答
0

要验证全名,代码如下:

- (BOOL)isFullNameValid: (NSString *) name {

NSString *nameRegex = @"^[A-Za-z]+(?:\\s[A-Za-z]+)*$";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
BOOL isValid = [nameTest evaluateWithObject:name];
return isValid;
}
于 2020-01-23T15:05:34.207 回答
-1
BOOL check=NO;
for(int i=0;i<[txt.text length];i++)
{
if([txt.text characterAtIndex:i]<=64 && [txt.text characterAtIndex:i]>=33)
{
    check=YES;

}else if([txt.text characterAtIndex:i]<=122 && [txt.text characterAtIndex:i]>=65)
{
    if([txt.text characterAtIndex:i]<=96 && [txt.text characterAtIndex:i]>=91)
    {
        check=YES;

    }

}
}
if(check==YES)
{
    [self alert:@"Name Contain spetial character"];
    return NO;

}else
{
    [self alert:@"Name Inserted succesfully"];

    return YES;
}
return  NO;
于 2014-10-01T06:31:08.087 回答
-1
 func nameValidation() -> Bool {
    let RegEx = "[a-zA-Z ]{2,15}"
    let name = NSPredicate(format:"SELF MATCHES %@", RegEx)
    return name.evaluate(with: self)
}
于 2018-05-17T05:18:31.830 回答