NSPredicate Whitespace在字符串中忽略

时间:2016-04-01 09:49:42

标签: ios cocoa-touch nspredicate

我的代码下面有字符串验证但第四个字符我想忽略用户输入的任何空格,因此字符串的长度增加一个字符。

- (BOOL)validatePancard:(NSString *)candidate
{
    NSString *panCardRegex = @"[A-Z]{5}[0-9]{4}[A-Z]{1}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", panCardRegex];
    NSLog(@"valid : %d", [emailTest evaluateWithObject:candidate]);
    return [emailTest evaluateWithObject:candidate];
}   

提前致谢。

2 个答案:

答案 0 :(得分:1)

只需实施以下代码即可。

BOOL isValid = [self validatePancard:@"ABC 5ZEXZ TRE"];


- (BOOL)validatePancard:(NSString *)candidate
{
    NSMutableString *a = [NSMutableString stringWithString:candidate];
    NSRange range;
    range.location = 3; //Remove Character at forth position
    range.length = 1; // number of character you want to remove
    [a deleteCharactersInRange:range];

    NSString *strImmutableString = [NSString stringWithString:a];

    NSString *panCardRegex = @"[A-Z]{5}[0-9]{4}[A-Z]{1}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", panCardRegex];
    NSLog(@"valid : %d", [emailTest evaluateWithObject:strImmutableString]);
    return [emailTest evaluateWithObject:candidate];
}

答案 1 :(得分:0)

//你可以使用其中任何一个: -

////1)

NSString *YourOldString = @"Please    Don't Kill        Me";

NSString *NewString = [YourOldString stringByReplacingOccurrencesOfString:@"\\s" withString:@""  options:NSRegularExpressionSearch range:NSMakeRange(0, [YourOldString length])];

NSLog(@"Your New String is %@",NewString);

//2).
NSArray* YourArray = [YourOldString componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]];

NSString* StringWithSpcs = [YourArray componentsJoinedByString:@""];

NSLog(@"The String is %@",StringWithSpcs);

//Or

//3).to remove only a given character from your string Use This

[YourOldString stringByReplacingOccurrencesOfString:@" " withString:@""];