Searching for substrings (NSString)
What's the best way to search for substring that are enclosed by ## $$. So for example, I have some text like this:
Lorem ##ipsum$$ dolor sit amet, ##consectetur$$ adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
I want to get the words ipsum and consectetur. I know I can do NSString rangeofs开发者_开发问答ubstring method, but is there a better way to do this? Basically, find a string enclosed by 2 other strings? Thanks
Your can use NSRegularExpression
(warning: iOS4+ only) to match your substrings using a RegEx pattern (like @"##.*$$"
typically).
It is then really easy to iterate thru the resulting matches (my preferred way is using an enumeration block, as we are un iOS4 :-)):
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"##(.*)$$" options:NSRegularExpressionCaseInsensitive error:nil];
[regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:
^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {
NSRange range = [match rangeAtIndex:1]; // range of string in first parens
NSString* oneWord = [yourString substringWithRange:range];
}
];
Note: If you need to support pre-iOS4 versions, you can check NSPredicate
but it is much less flexible (... and I guess that for pre-iOS4, using rangeOfSubstring is probably the best choice anyway as NSPredicate will only tell you if a string is matching but won't allow you to get the substring...)
Iterate through string characters, searching for '##', and after that search for nearest '$$'.
精彩评论