iPhone,NSRegularExpression大浮

时间:2012-09-07 13:00:12

标签: iphone objective-c regex parsing nsregularexpression

我有以下代码:

-(NSString*)getNumberFromString(NSString*)theString{
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"rhs: \"([0-9]*[.]*[0-9]*)" options:NSRegularExpressionCaseInsensitive | NSRegularExpressionAnchorsMatchLines error:&error];
    NSArray *matches = [regex matchesInString:theString options:0 range:NSMakeRange(0, [theString length])];
    NSTextCheckingResult *match = [matches objectAtIndex:0];
    return [theString substringWithRange:[match rangeAtIndex:1]]);
}

当我尝试解析此字符串时:

{lhs: "1 example", rhs: "44.5097254 Indian sample", error: "", icc: true}

我得到了结果44.5097254

但对于这个字符串:

{lhs: "1 example", rhs: "44.5097254.00.124.2 sample", error: "", icc: true}

我的44结果不正确。我希望得到44.5097254.00.124.2

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您要查找的正则表达式是rhs: \"(\d+(?:\.\d+)*)

-(NSString*)getNumberFromString:(NSString*)theString
{
    NSError *error = NULL;
    NSRegularExpression *regex =
    [NSRegularExpression regularExpressionWithPattern:@"rhs: \"(\\d+(?:\\.\\d+)*)"
                                              options:NSRegularExpressionCaseInsensitive | NSRegularExpressionAnchorsMatchLines
                                                error:&error];

    NSArray *matches = [regex matchesInString:theString
                                      options:0
                                        range:NSMakeRange(0, [theString length])];

    NSTextCheckingResult *match = [matches objectAtIndex:0];
    return [theString substringWithRange:[match rangeAtIndex:1]];
}

...
     NSLog(@"%@", [self getNumberFromString:
                   @"{lhs: \"1 example\", rhs: \"44.5097254.00.124.2 sample\", error: \"\", icc: true}"]);

输出: 44.5097254.00.124.2

答案 1 :(得分:1)

就像我在上一个问题中编辑的那样,在正则表达式的末尾添加一个*来做事情:

  -(NSString*)getNumberFromString(NSString*)theString{
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"rhs: \"(([0-9]*[.]*[0-9]*)*)" options:NSRegularExpressionCaseInsensitive | NSRegularExpressionAnchorsMatchLines error:&error];
    NSArray *matches = [regex matchesInString:theString options:0 range:NSMakeRange(0, [theString length])];
    NSTextCheckingResult *match = [matches objectAtIndex:0];
    return [theString substringWithRange:[match rangeAtIndex:1]]);

}

对于未来,请尝试了解答案的作用。只需复制代码并认识到它不符合您的要求即可。但首先要自己做一些研究。您可以很容易地看到,添加星形将使表达式适用于每个长度的值。