我混淆了NSString
让我们说
dsadasdasd"my_id": "qwerr"dcdscsdcds"my_id": "oytuj"adasddasddsddaS"my_id": "sjghjgjg"ddsfsdfsdf
如何找到
之间的每个字符串实例"my_id": "
和下一个
"
所以在这里,我希望结果是NSArray
:
qwerr
oytuj
sjghjgjg
我正在寻找提示,正则表达式或任何其他解决方案都会很好。我尝试了很多方法来使用NSRange
和substringWithRange
组合但无法使其发挥作用:(
帮助将不胜感激!感谢
答案 0 :(得分:3)
我忽略了收盘报价要求。那么,在这种情况下,有或没有正则表达式的代码的长度相似。
这是一个正则表达式建议,基本上提取"my_id": "
之后的所有子字符串,直到下一个"
或字符串结尾:
NSError *error = nil;
NSString *pattern = @"\"my_id\": \"([^\"]+)";
NSString *string = @"dsadasdasd\"my_id\": \"qwerr\"dcdscsdcds\"my_id\": \"oytuj\"adasddasddsddaS\"my_id\": \"sjghjgjg\"ddsfsdfsdf";
NSRange range = NSMakeRange(0, string.length);
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:range];
for (NSTextCheckingResult* match in matches) {
NSRange group1 = [match rangeAtIndex:1];
NSLog(@"group1: %@", [string substringWithRange:group1]);
}
请参阅IDEONE demo
答案 1 :(得分:0)
答案 2 :(得分:0)
你的标题是“巨大的”字符串。我假设你不知道会发生多少次。
我会使用NSMutableString
和NSRange
。请参阅NSMutableString
documentation,NSString
doc和NSRange
doc。
免责声明:此代码未经测试且不使用正则表达式,因为这是一种替代方法,正则表达式可能不是正确的解决方案(由其他评论者支持)。
NSMutableString *string = //mutable copy of however you get the "jumbled" string
//To get the mutable copy use [string mutableCopy]
NSMutableArray *array = [NSMutableArray array]; //new array
NSRange *range = [string rangeOfString:@"\"my_id\": \""]; //find the my_id part
while (range.location != -1){ //if not found, location is -1
//delete the irrelevant parts of the string (you should keep a copy of the original)
//the length of the my_id part is 10
[string deleteCharactersInRange:NSMakeRange(0, range.location - 1 + 10)];
NSRange *end = [string rangeOfString:@"\""]; //find the next " char
NSString *str = [string substringToIndex:end.location]; //get the relevant part
[array addObject:str]; //save it
[string deleteCharactersInRange:NSMakeRange(0, end.location)];
range = [string rangeOfString:@"\"my_id\": \""];
}