Objective c 如何解开绳子?
我有一个很长的字符串,我只想提取该字符串中的某些字符串。我该怎么做 例如,我有:Objective c 如何解开绳子?,objective-c,nsstring,substring,Objective C,Nsstring,Substring,我有一个很长的字符串,我只想提取该字符串中的某些字符串。我该怎么做 例如,我有: this is the image <img src="http://vnexpress.net/Files/Subject/3b/bd/67/6f/chungkhoan-xanhdiem2.jpg"> and it is very beautiful. 这是图像,非常漂亮。 是的,现在我想得到这个长字符串的子字符串,并且只得到http://vnexpress.net/Files/Subject/3
this is the image <img src="http://vnexpress.net/Files/Subject/3b/bd/67/6f/chungkhoan-xanhdiem2.jpg"> and it is very beautiful.
这是图像,非常漂亮。
是的,现在我想得到这个长字符串的子字符串,并且只得到http://vnexpress.net/Files/Subject/3b/bd/67/6f/chungkhoan-xanhdiem2.jpg
请告诉我如何做到这一点。您应该使用正则表达式,可能使用类 下面是一个完全符合您要求的示例(来自):
NSString*urlString=nil;
NSString*htmlString=//您的字符串;
NSScanner*scanner=[NSScanner scannerWithString:htmlString];
[扫描程序扫描字符串:@”“;
[扫描程序扫描到CharactersFromSet:charset-intoString:&urlString];
}
NSLog(@“%@”,urlString);
您可以为此使用正则表达式:
NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:@"src=\"([^\"]*)\"" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *text = @"this is the image <img src=\"http://vnexpress.net/Files/Subject/3b/bd/67/6f/chungkhoan-xanhdiem2.jpg\"> and it is very beautiful.";
NSArray *imgs = [regex matchesInString:text options:0 range:NSMakeRange(0, [text length])];
if (imgs.count != 0) {
NSTextCheckingResult* r = [imgs objectAtIndex:0];
NSLog(@"%@", [text substringWithRange:[r rangeAtIndex:1]]);
}
它匹配src
属性的内容,并捕获引号之间的内容(注意一对括号)。然后在[r rangeAtIndex:1]
中检索此标题,并用于提取您要查找的字符串部分
NSString *urlString = nil;
NSString *htmlString = //Your string;
NSScanner *scanner = [NSScanner scannerWithString:htmlString];
[scanner scanUpToString:@"<img" intoString:nil];
if (![scanner isAtEnd]) {
[scanner scanUpToString:@"http" intoString:nil];
NSCharacterSet *charset = [NSCharacterSet characterSetWithCharactersInString:@">"];
[scanner scanUpToCharactersFromSet:charset intoString:&urlString];
}
NSLog(@"%@", urlString);
NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:@"src=\"([^\"]*)\"" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *text = @"this is the image <img src=\"http://vnexpress.net/Files/Subject/3b/bd/67/6f/chungkhoan-xanhdiem2.jpg\"> and it is very beautiful.";
NSArray *imgs = [regex matchesInString:text options:0 range:NSMakeRange(0, [text length])];
if (imgs.count != 0) {
NSTextCheckingResult* r = [imgs objectAtIndex:0];
NSLog(@"%@", [text substringWithRange:[r rangeAtIndex:1]]);
}
src="([^"]*)"