NSRegularExpression for retrieving numbers from a string
I had used NSScanner for retrieving numbers from below text. But sometimes the result is not like what is expected. Heard that NSRegularExpres开发者_如何学Gosion class which is available fro iOS 4 is better to do this type of extraction. As I am a beginner on NSRegularExpression, I found the documentation provided by Apple is difficult to understand. Any help will be greatly appreciated. Thanks.
Input:
1D03 04 10 17 47 D24--
Output:
03 04 10 17 47 24
The first 5 sets of numbers should be less than 59 and last set should be less than 39.
try this ..
NSString *originalString = @"1D03 04 10 17 47 D24---";
NSLog(@"%@", originalString);
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:@"0123456789 "];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
NSLog(@"%@", strippedString);
Or this:
NSString *string = @"1D03 04 10 17 47 D24---";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\S*(\\d{2})\\S*"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:@"$1"];
This Regular Expression matches everything which starts and ends with 0 or more non withspace Charcters (\S) and has in the middle two digits (\d). The matches are replaced by the tow digits in the middle of the string.
精彩评论