这是我的示例字符串,是从远程服务器解析的:

NSString *example = @"#parsed Value1:1a 2013-02-20 10:00:00 UTC Value2=2a Value3=3a Value4=4aKm Value5=A"

我需要从上面的字符串(不带其他字符)中推断出单个ValueS:
"1a"
"2013-02-20 10:00:00 UTC"
"2a"
"3a"
"4a"
"A"

请为我建议正确的代码(我尝试过使用正则表达式未成功),谢谢!

最佳答案

如果格式保持不变,则无需使用正则表达式。

尝试使用NSScanner,尤其是scanUpToString:intoString:scanString:intoString:方法

编辑:

此代码应该是您所需要的:

NSString *example = @"#parsed Value1:1a 2013-02-20 10:00:00 UTC Value2=2a Value3=3a Value4=4aKm Value5=A";

NSString *temp, *value1, *date, *value2, *value3, *value4, *value5;
NSScanner *scanner = [NSScanner scannerWithString:example];
// By default, NSScanner will skip whitespace - we don't want it to skip anything here
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@""]];
[scanner scanString:@"#parsed Value1:" intoString:&temp];
[scanner scanUpToString:@" " intoString:&value1];
[scanner scanString:@" " intoString:&temp];
[scanner scanUpToString:@" Value2=" intoString:&date];
[scanner scanString:@" Value2=" intoString:&temp];
[scanner scanUpToString:@" Value3=" intoString:&value2];
[scanner scanString:@" Value3=" intoString:&temp];
[scanner scanUpToString:@" Value4=" intoString:&value3];
[scanner scanString:@" Value4=" intoString:&temp];
[scanner scanUpToString:@" Value5=" intoString:&value4];
[scanner scanString:@" Value5=" intoString:&temp];
value5 = [example substringFromIndex:[scanner scanLocation]];

关于ios - 从某些解析的NSString中提取文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14981817/

10-11 02:04