iOS-正则表达式用作筛选

来源:互联网 发布:搜狐网络大厦 邮编 编辑:程序博客网 时间:2024/06/05 10:27

需求:实现一个只能输入英文和数字的输入框,并且必须是英文开头(纯英文,英文+数字,但不能是‘xml’)

实现:

- (void)textFieldDidEndEditing:(UITextField *)textField Cell:(MetadataCell *) cell{        //if ([textField.superview.superview isMemberOfClass:[MetadataCell class]])    if(cell != NULL)    {        //MetadataCell *cell = (MetadataCell*)textField.superview.superview;                if(cell == nil)            NSLog(@"empty cell");        NSString *cellText = [NSString  stringWithString: cell.textContext.text];        NSString *cellKey = [NSString stringWithString: cell.textKey.text];        //NSLog(@"cellText = %@",cellText);        NSIndexPath *indexPath = [self.m_table indexPathForCell:cell];                if(indexPath.section == 0)        {            switch (indexPath.row)            {                case 0:                    [BasicMetaData setValue:cellText forKey:@"Title"];                    break;                case 1:                    [BasicMetaData setValue:cellText forKey:@"Crew"];                    break;                case 2:                    [BasicMetaData setValue:cellText forKey:@"Description"];                    break;                default:                    break;            }        }        //NSLog(@"BasicMetaData = %@",BasicMetaData);        if(indexPath.section == 1)        {            if (cellKey) {                if ([self beginWithLetter:cellKey] == YES) {                    if ([cellKey hasPrefix:@"xml"]) {                        NSString *message = NSLocalizedString(@"Key is only allowed with letters start (exclude ‘xml’)",nil);                        [self showAlertWhenCustomMetadataKeyIsInvalid:message andCell:cell];                    }                }else{                                        NSString *message = NSLocalizedString(@"Key is only allowed with letters start (exclude ‘xml’)",nil);                    [self showAlertWhenCustomMetadataKeyIsInvalid:message andCell:cell];                }            }                        NSArray *array = [NSArray arrayWithObjects:cellKey,cellText,nil];            CusMetaData[indexPath.row] = [NSArray arrayWithArray:array];        }        //NSLog(@"CusMetaData = %@",CusMetaData);    }    [m_table reloadData];}//  判断是否以字母开头(正则判断)- (BOOL)beginWithLetter:(NSString *)str {    NSString *regular = @"^[A-Za-z]|^[A-Za-z].+$";    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regular];    if ([predicate evaluateWithObject:str] == YES){        return YES;    }else{        return NO;    }}