大家好,我正在尝试在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;
答案 0 :(得分:5)
我明白了:
NSString *nameRegex = @"[a-zA-z]+([ '-][a-zA-Z]+)*$";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
BOOL isValid = [nameTest evaluateWithObject:name];
return isValid;
答案 1 :(得分:2)
这种方法对我有用:
-(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;
}
答案 2 :(得分:0)
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;
答案 3 :(得分: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
}
答案 4 :(得分:0)
要验证全名,代码是这样的:
rm -rf ~/.cargo/registry
答案 5 :(得分:-1)
func nameValidation() -> Bool {
let RegEx = "[a-zA-Z ]{2,15}"
let name = NSPredicate(format:"SELF MATCHES %@", RegEx)
return name.evaluate(with: self)
}