简体   繁体   中英

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 AZ letters.

What am I doing wrong?

It needs to grab all the letters only. No weird characters and no numbers, just AZ 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
                                        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

I think you need to drop the perl syntax on the regexp. Use @"[^AZ]" as the match string.

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]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM