修剪NSString

时间:2013-02-08 21:34:44

标签: ios regex nsregularexpression

我正在通过以下方式修剪NSString

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"X = (\\d+.\\d+), Y = (\\d+.\\d+), (%@)" options:0 error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:txt.text options:0 range:NSMakeRange(0, [txt.text length])];
if (match) {
    NSRange firstHalfRange = [match rangeAtIndex:1];
    NSString *xString = [txt.text substringWithRange:firstHalfRange];
    NSRange secondHalfRange = [match rangeAtIndex:2];
    NSString *yString = [txt.text substringWithRange:secondHalfRange];
    NSRange thirdHalfRange = [match rangeAtIndex:3];
    NSString *colorString = [txt.text substringWithRange:thirdHalfRange];

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

NSString看起来像这样:

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

除了可能改变的X和Y数之外,Y = 295.000000 X = 207.500000的部分总是相同的,以及:TheWhite,它可能变为例如。 TheBlack

使用此方法,我成功提取了X和Y值,但没有提取最终字符串。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您的模式以(%@)结尾。我应该以{{1​​}}代替。