In Objective C, what's the best way to extract multiple substrings of text around multiple patterns?

你离开我真会死。 提交于 2019-11-29 18:07:21

You could use regular expressions provided by a third party framework (e.g. RegexKit or RegexKitLite). To create the RE, join the patterns with "|" and prepend and append parentheses and patterns to capture context. Match the string against the regexp.

Some example prefix & suffix patterns:

  • ".{,15}(", ").{,15}" to match up to 15 characters
  • "(\w+\W+){,4}(", ")(\W+\w+){,4}" to match up to 4 words

I think what you want is NSScanner. To find an arbitrary string within a larger string, you do something like:

 NSString *scannedString = nil;
 NSScanner *scanner = [NSScanner scannerWithString:@"The quick brown fox jumped over the lazy dog"];
 [scanner scanUpToString:@"brown" intoString:&scannedString];
 // scannedString is now @"The quick " and the scanner's location is right before "brown"

To get the context, you'll need to decide how much around the location where "brown" was found you want to include in your result.

As an alternate solution when you're always looking for words, you could use NSString's componentsSeparatedByString: to get an array and then return the element + x many elements around it. For example:

 NSArray *words = [@"The quick brown fox jumped over the lazy dog" componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet];
 NSUInteger wordLocation = [words indexOfObject:@"brown"];
 NSString *wordInContext = [[words subarrayWithRange:NSMakeRange(brownlocation-2, brownLocation+2)] componentsJoinedByString:@" "];

(All the examples here are lacking necessary error checking, but it's just to give you an idea of ways you can do things like this.)

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