开发者

String matching objective-c

I need to match my string in this way: *myString* where * mean any substring. which method shou开发者_开发技巧ld I use?

can you help me, please?


If it's for iPhone OS 3.2 or later, use NSRegularExpressionSearch.

NSString *regEx = [NSString stringWithFormat:@".*%@.*", yourSearchString];
NSRange range = [stringToSearch rangeOfString:regEx options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {

}


You can't do an actual search using a * (wildcard character), but you can usually do something that is equivalent:

Equivalent to searching for theTerm*:

if ([theString hasPrefix:@"theTerm"]) {

Equivalent to searching for *theTerm:

if ([theString hasSuffix:@"theTerm"]) {

Or, using the category on NSString shown below, the following is equivalent to searching for *theTerm*:

if ([theString containsString:@"theTerm"]) {

A category is simply a new method (like a function) that we add to class. I wrote the following one because it generally makes more sense to me to think of one string containing another rather than dealing with NSRanges.

// category on NSString
@interface NSString (MDSearchAdditions)
- (BOOL)containsString:(NSString *)aString;
@end

@implementation NSString (MDSearchAdditions)

- (BOOL)containsString:(NSString *)aString {
  return [self rangeOfString:aString].location != NSNotFound;
}

@end


If you need something more evolved, try https://github.com/dblock/objc-ngram.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜