views:

229

answers:

1

I'd like to create a regular expression that will match and return based on the following criteria:

1) I have N search terms entered by a user

2) I have a body of text.

3) I want to return a list of all the occurrences of all the search terms entered by the user plus surrounding context. I think (\w+\W+){,4}(", ")(\W+\w+){,4} might work.

4) I don't know how to use RegexKitLite at all. Do I invoke a RegexKitLite class? or does it interface into NSString somehow?

+1  A: 

RegexKitLite defines a category on NSString. To get an array of substrings matching a pattern, use componentsMatchedByRegex:, as shown in the "Creating an Array of Every Match" section of the documentation.

NSArray *words = [NSArray arrayWithObjects:@"brown",@"lazy",nil];
NSString *pattern = [NSString stringWithFormat:@"(\\w+\\W+){0,4}(%@)(\\W+\\w+){0,4}",[words componentsJoinedByString:@"|"]];
NSString *text = @"the quick brown fox jumped over the lazy dog";
NSArray *matches = [text componentsMatchedByRegex:pattern];
outis
thanks. this answer works, however, i ended up using "(\\w+\\W+){0,5}(%@).{0,20}" as the pattern and NSArray *matches = [txt componentsMatchedByRegex:pattern options:RKLCaseless range:NSMakeRange(0UL, [txt length]) capture:0 error:NULL]to do the searching, as i needed a case insensitive search. If there were an easier way to make this search caseless, i'd be interested.
Matt
also, i changed the second word match to a 20 character match because the latter pattern as you described it would end with the search terms, for some reason... so, if you searched for "fox" you would get "the quick brown fox" and nothing after fox. By swapping it to ".{0,20}" i at least get something after.
Matt