1

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

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"

请建议我正确的代码来做到这一点(我已经尝试过使用正则表达式但没有成功),谢谢!

4

3 回答 3

2

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

尝试使用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]];
于 2013-02-20T14:25:26.660 回答
1

这些确切键名的正则表达式类似于:

#parsed Value1:(.*) (.*) Value2=(.*) Value3=(.*) Value4=(.*) Value5=(.*)

如果列表是可变长度的,则可以在其中进行分组。()?如果需要任意键,则需要分组并重复可以检测到key=value模式的内容。

于 2013-02-20T14:13:58.580 回答
-1

也可以使用 NSScanner 查看link1link2

于 2013-02-20T14:28:59.817 回答