iOS 如何在一个巨大的字符串中查找两个字符串之间的多个字符串?

iOS How to find multiple strings between 2 strings in a huge string?

我有一个乱码NSString比方说

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

如何找到

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

和下一个

"

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

qwerr
oytuj
sjghjgjg

我正在寻找提示,正则表达式或任何其他解决方案都不错。我尝试了多种使用 NSRangesubstringWithRange 组合的方法,但无法正常工作。

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

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

Regex live here.

或者这样:

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

希望对您有所帮助。

您的标题显示 "huge" 字符串。我假设你不知道会出现多少次。

我会使用 NSMutableStringNSRange。见 NSMutableString documentation, NSString doc, and 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\": \""];
}

我忽略了收盘价要求。那么,在这种情况下,使用或不使用正则表达式的代码在长度上是相似的。

这是一个正则表达式建议,基本上提取 "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