简体   繁体   中英

NSRegularExpression searching for unknown value

So I am working on an iPhone app, and it takes a picture of some text, the picture gets OCR'ed and sent back to me, and I then I use a regular expression to search the string for double values up to xxxx.xx.

NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:@"\\d?\\d?\\d?\\d?\\.\\d?\\d?"
                              options:0
                              error:&error];

NSRange range   = [regex rangeOfFirstMatchInString:result
                                           options:0
                                             range:NSMakeRange(0, [result length])];

if([result length] > 0)
{
    NSString *subString = [result substringWithRange:range];

    double r = [subString doubleValue];

Right now it is working as I want, but it only gets the first number it comes to. There could be an indeterminate number of doubles, and I need to get the largest one. What would be the best way to go about that?

Use matchesInString:options:range: instead of rangeOfFirstMatchInString. This will give you an array of NSTextCheckingResult objects, from which you can extract the range.

NSRegularExpression *regex = [NSRegularExpression
                                   regularExpressionWithPattern:@"\\d?\\d?\\d?\\d?\\.\\d?\\d?"
                                   options:0
                                   error:&error];
    NSArray *arr = [regex matchesInString:string options:NSMatchingReportCompletion range:NSMakeRange(0,string.length)];
    for (NSTextCheckingResult *obj in arr) {
        double r = [[string substringWithRange:obj.range] doubleValue];
        NSLog(@"%f",r);
    }

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