Search in a NSString for words that begin with specific text and end with a "

独自空忆成欢 提交于 2019-12-10 21:06:58

问题


I have a NSString that contains the html code of a webpage. Now, how do i search on the whole string for all the words that start with 'data-src="http://' and end with a " ? I'll save them in an array. My string is called urlPage

PS: i dont want the words to have the 'data-src="http://' and " . I just want the words between these 2


回答1:


Here is some example code:

NSString *string;
NSString *pattern;
NSRegularExpression *regex;

string = @" aa data-src=\"http://test1\" cd data-src=\"http://test2\" cd";
pattern = @"data-src=\"http://([^\"]+)\"";

regex = [NSRegularExpression
         regularExpressionWithPattern:pattern
         options:NSRegularExpressionCaseInsensitive
         error:nil];

NSArray *matches = [regex matchesInString:string
                                  options:0
                                    range:NSMakeRange(0, [string length])];

for (NSTextCheckingResult *match in matches) {
    NSRange range = [match rangeAtIndex:1];
    NSLog(@"match: '%@'", [string substringWithRange:range]);
}

NSLog output:
match: 'test1'
match: 'test2'




回答2:


Your best bet is to use NSRegularExpression to search for string. Especially the enumerateMatchesInString:options:range:usingBlock: method. In this method you'll get the result that fits your regex and you can manually strip out the beginning part and the question mark if you want.



来源:https://stackoverflow.com/questions/9268795/search-in-a-nsstring-for-words-that-begin-with-specific-text-and-end-with-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!