这是我的示例字符串,从远程服务器解析:
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"
请建议我使用正确的代码(我尝试使用正则表达式没有成功),谢谢!
答案 0 :(得分: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]];
答案 1 :(得分:1)
这些确切键名的正则表达式如下:
#parsed Value1:(.*) (.*) Value2=(.*) Value3=(.*) Value4=(.*) Value5=(.*)
如果列表是可变长度的,您可以在()?
内进行分组如果您需要任意键,则需要对可以检测key=value
模式的内容进行分组和重复。
答案 2 :(得分:-1)