13

I need to match my string in this way: *myString* where * mean any substring. which method should I use?

can you help me, please?

martin clayton
  • 76,436
  • 32
  • 213
  • 198
Dany
  • 2,290
  • 8
  • 35
  • 56
  • @Mitch Wheat, it's "which method should I use?" "can you help me, please" is probably rhetorical, though I guess you could answer that too. – Dan Rosenstark Dec 21 '10 at 00:08

3 Answers3

25

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) {

}
Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
  • I try to use your code but it don't work, but if I use in this way: NSRange range = [@"hello pippo" rangeOfString:@".*pi.*" options:NSRegularExpressionSearch]; it work!! Why? In particular if I use regEx to rangeOfString id don't work!?!?!?! – Dany Dec 21 '10 at 10:03
  • 1
    I noticed that it don't work if textView.text is only a word!! – Dany Dec 21 '10 at 10:13
  • @user536926 sorry fixing now. – Dan Rosenstark Dec 22 '10 at 05:37
11

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
NSGod
  • 22,699
  • 3
  • 58
  • 66
0

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

dB.
  • 4,700
  • 2
  • 46
  • 51