iOS如何在巨大的字符串中找到2个字符串之间的多个字符串?

时间:2015-10-27 09:53:30

标签: ios objective-c regex nsstring substring

我混淆了NSString让我们说

dsadasdasd"my_id": "qwerr"dcdscsdcds"my_id": "oytuj"adasddasddsddaS"my_id": "sjghjgjg"ddsfsdfsdf

如何找到

之间的每个字符串实例
"my_id": "

和下一个

"

所以在这里,我希望结果是NSArray

qwerr
oytuj
sjghjgjg

我正在寻找提示,正则表达式或任何其他解决方案都会很好。我尝试了很多方法来使用NSRangesubstringWithRange组合但无法使其发挥作用:(

帮助将不胜感激!感谢

3 个答案:

答案 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)

你可以试试这样的正则表达式:

"my_id": "\K[^"]+

Regex live here.

或者这个:

(?<="my_id": ")[^"]+

希望它有所帮助。

答案 2 :(得分:0)

你的标题是“巨大的”字符串。我假设你不知道会发生多少次。

我会使用NSMutableStringNSRange。请参阅NSMutableString documentationNSString docNSRange 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\": \""];
}