问题
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