How to get regex to grab all letters from an objective c string?
I'm trying to get the following regular expression to grab only the letters from an alpha-numeric character input box, however it's always returning the full string, and not any of the A-Z letters.
What am I doing wrong?
It needs to grab all the letters only. No weird characters and no numbers, just A-Z and put it into a string for me to use later on.
// A default follows
NSString *TAXCODE = txtTaxCode.text;
// Setup default for taxcode
if ([TAXCODE length] ==0)
{
TAXCODE = @"647L";
}
NSError *error = NULL;
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:@"/[^A-Z]/gi"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSLog(@"TAXCODE = %@", TAXCODE);
NSLog(@"TAXCODE.length = %d", [TAXCODE length]);
NSLog(@"STC (before regex) = %@", STC);
STC = [regex stringByReplacingMatchesInString:TAXCODE
options:0
开发者_JAVA技巧 range:NSMakeRange(0, [TAXCODE length])
withTemplate:@""];
NSLog(@"STC (after regex) = %@", STC);
My debug output is as follows:
TAXCODE = 647L
TAXCODE.length = 4
STC (before regex) =
STC (after regex) = 647L
If you only ever going to have letters on one end then you could use.
NSString *TAXCODE =@"647L";
NSString *newcode = [TAXCODE stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
If intermixed letters then you can get an Array that you can then play with.
NSString *TAXCODE =@"L6J47L";
NSArray *newcodeArray = [TAXCODE componentsSeparatedByCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
I think you need to drop the perl syntax on the regexp. Use @"[^A-Z]" as the match string.
精彩评论