Compy
Compy

Reputation: 1177

Find an 8 digit string within a string - Objective C

So I have a string that's come out of an OCR library like so:

ALLee;YIeiqm Y E JOHNSON-TEST g jammima g 02345678 8;;Y_(____. g GHJ- 444 4333333333 * BAKERY -- Scones p ii

I want to search through this string and find the "02345678" part. This string can be anything but it is always 8 characters long and all the characters are together. How can I search through the string to find the 1st occurrence of an 8 character contant string without a space or character that isn't in the ranges of A to Z and 0 to 9?

Thanks!

Adam

Upvotes: 2

Views: 139

Answers (1)

trojanfoe
trojanfoe

Reputation: 122391

NSString *yourString = @"ALLee;YIeiqm Y E JOHNSON-TEST g jammima g 02345678 8;;Y_(____. g GHJ- 444 4333333333 * BAKERY -- Scones p ii";
NSRegularExpression *regex = [NSRegularExpression         
    regularExpressionWithPattern:@"[A-Za-z0-9]{8}"
    options:NSRegularExpressionCaseInsensitive
    error:&error];
[regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
    // your code to handle matches here
}];

(code shamelessly nicked from this SO answer).

Upvotes: 7

Related Questions