如何使用NSRegularExpression从字符串中提取数字

时间:2012-11-27 05:43:49

标签: iphone objective-c nsregularexpression

我想从下面的字符串中提取数字81698,但是我遇到了一些困难。

这是我的代码。

NSString *content = @"... list.vars.results_thpp = 32;
                          list.vars.results_count = 81698;
                          list.vars.results_board = '12'; ...";

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"results_count.*[0-9*];"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];



NSString *modifiedString = [regex stringByReplacingMatchesInString:content
                                                           options:0
                                                             range:NSMakeRange(0, [content length])
                                                      withTemplate:@"$1"];

输出就是这个

... list.vars.results_thpp = 32;
    list.vars.
    list.vars.results_board = '12'; ...

但我只想要81698

我做错了什么?

1 个答案:

答案 0 :(得分:2)

NSString *content = @"... list.vars.results_thpp = 32;list.vars.results_count = 81698;list.vars.results_board = '12'; ...";
NSString *param = nil;
NSRange start = [content rangeOfString:@"list.vars.results_count = "];
if (start.location != NSNotFound) {
    param = [content substringFromIndex:start.location + start.length];
    NSRange end = [param rangeOfString:@";"];
    if (end.location != NSNotFound) {
        param = [param substringToIndex:end.location];
    }
}
NSLog(@"param:%@", param);

我认为这会对你有所帮助。