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]]);
}

当我尝试解析这个字符串时:

{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.

我究竟做错了什么?

4

2 回答 2

2

您正在寻找的正则表达式是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

于 2012-09-07T13:07:17.293 回答
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]]);

}

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

于 2012-09-07T13:34:42.053 回答