Graphics Programs Reference
In-Depth Information
For practice with these classes, let's create an NSRegularExpression that looks for
RSSItem s that contain the word Author in the title. This will get us all of the original
posts; replies to posts contain the word Reply in their titles instead of Author . In
RSSChannel.m , enter the following code for trimItemTitles .
- (void)trimItemTitles
{
// Create a regular expression with the pattern: Author
NSRegularExpression *reg =
[[NSRegularExpression alloc] initWithPattern:@"Author"
options:0
error:nil];
// Loop through every title of the items in channel
for (RSSItem *i in items) {
NSString *itemTitle = [i title];
// Find matches in the title string. The range
// argument specifies how much of the title to search;
// in this case, all of it.
NSArray *matches = [reg matchesInString:itemTitle
options:0
range:NSMakeRange(0, [itemTitle length])];
// If there was a match...
if ([matches count] > 0) {
// Print the location of the match in the string and the string
NSTextCheckingResult *result = [matches objectAtIndex:0];
NSRange r = [result range];
NSLog(@"Match at {%d, %d} for %@!", r.location, r.length, itemTitle);
}
}
}
In this code, you first create the expression and initialize it with the pattern you're seek-
ing. Then, for each RSSItem , you send the matchInString:options:range:
message to the regular expression passing the item's title as the string to search. Finally,
for each title, we only expect one match, so we get the first NSTextCheckingResult
in the matches array, get its range, and log it to the console.
Build and run the application. Check the console output after all of the items are pulled
down from the server. You should see only items for original posts.
Constructing a pattern string
In the regular expression you just created, the pattern consisted solely of a literal string.
That's not very powerful or flexible. But we can combine the literal strings with symbols
Search WWH ::




Custom Search