从NSStrings中提取数字

时间:2013-02-07 18:36:18

标签: ios xcode

我有很多NSString,看起来像这样:

@"this is the content. The content of this string may vary, as well as the length, and my include any characters, with numbers Y = 295.000000 X = 207.500000"

除了可能改变的X和Y数字之外,Y = 295.000000 X = 207.500000的部分总是相同的。

我需要以某种方式来获取这些数字并做这样的事情:

coordsFinal.x = 295.000000;
coordsFinal.y = 207.500000;

格式为:

coordsFinal.x = [NSString stringWithFormat: @"%@", trimmed string];

任何想法??

2 个答案:

答案 0 :(得分:5)

您可以使用正则表达式来提取数字:

NSString *string = ...; // Your string
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"Y = (\\d+.\\d+) X = (\\d+.\\d+)" options:0 error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
if (match) {
    NSRange yRange = [match rangeAtIndex:1];
    NSString *yString = [string substringWithRange:yRange];
    NSRange xRange = [match rangeAtIndex:2];
    NSString *xString = [string substringWithRange:xRange];

    NSLog(@"X = %@, Y = %@", xString, yString);
}

输出:

X = 207.500000, Y = 295.000000

答案 1 :(得分:0)

您只需要按照以下方法调用要修剪的字符串

 [yourstring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]