Reputation: 25701
I have an NSAttributedString like so:
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"EThis string shows my #tags. Click on a #tag now."];
What do I use to find the location and end of all tags? Is there a good regex for this or another better way in iOS?
Note: My definition of a tag starts with # and ends with the last alphanumeric character is hit. So a period (.), space, or dash would end the tag.
Thanks.
Upvotes: 0
Views: 606
Reputation: 53000
The class you need is NSRegularExpression
and the particular method that will give you the start and length of each match is matchesInString:options:range
.
Upvotes: 1
Reputation: 15015
If you want to extract the string then you can use NSScanner
class like that below:-
NSMutableAttributedString *mtStr = [[NSMutableAttributedString alloc]initWithString:@"EThis string shows my #tags. Click on a #tag now."];
NSString *string = mtStr.string;
// Set up convenience variables for the start and end tag;
NSString *startTag = @"#";
NSString *endTag = @".";
NSString *title;
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner scanUpToString:startTag intoString:nil];
[scanner scanString:startTag intoString:nil];
[scanner scanUpToString:endTag intoString:&title];
NSLog(@"Value is: %@", title);
Upvotes: 2
Reputation: 174706
Seems like you want something like this,
#.*?[A-Za-z0-9](?=[.\\s-])
or
#.*?[A-Za-z0-9](?=[. -])
The above regex would match all the strings which starts with #
then matches upto the first alphanumeric character which is immediately followed by a space or dot or dash.
Upvotes: 2