Skip to content

Instantly share code, notes, and snippets.

@elasticthreads
Created September 16, 2011 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elasticthreads/1222763 to your computer and use it in GitHub Desktop.
Save elasticthreads/1222763 to your computer and use it in GitHub Desktop.
nspredicate to find lines containing markdown reference links
- (NSArray *)referenceLinksInString:(NSString *)contentString{
NSString *wildString = @"*[*]:*http*"; //This is where you define your match string.
NSPredicate *matchPred = [NSPredicate predicateWithFormat:@"SELF LIKE[cd] %@", wildString];
/*
Breaking it down:
SELF is the string you're testing
[cd] makes the test case-insensitive
LIKE is one of the predicate search possiblities. It's NOT regex, but lets you use wildcards '?' for one character and '*' for any number of characters
MATCH (not used) is what you would use for Regex. And you'd set it up similiar to LIKE. I don't really know regex, and I can't quite get it to work. But that might be because I don't know regex.
%@ you need to pass in the search string like this, rather than just embedding it in the format string. so DON'T USE something like [NSPredicate predicateWithFormat:@"SELF LIKE[cd] *[*]:*http*"]
*/
NSMutableArray *referenceLinks=[NSMutableArray new];
//enumerateLinesUsing block seems like a good way to go line by line thru the note and test each line for the regex match of a reference link. Downside is that it uses blocks so requires 10.6+. Let's get it to work and then we can figure out a Leopard friendly way of doing this; which I don't think will be a problem (famous last words).
[contentString enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {
if([matchPred evaluateWithObject:line]){
// NSLog(@"%@ matched",line);
NSString *theRef=line;
//theRef=[line substring...] here you want to parse out and get just the name of the reference link we'd want to offer up to the user in the autocomplete
//and maybe trim out whitespace
theRef = [theRef stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//check to make sure its not empty
if(![theRef isEqualToString:@""]){
[referenceLinks addObject:theRef];
}
}
}];
//create an immutable array safe for returning
NSArray *returnArray=[NSArray array];
//see if we found anything
if(referenceLinks&&([referenceLinks count]>0))
{
returnArray=[NSArray arrayWithArray:referenceLinks];
}
[referenceLinks release];
return returnArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment