Search code examples
iosobjective-cregexnsstringnsattributedstring

Using a regex or other mechanism to find tags in a NSAttributedString (or NSString)


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.


Solution

  • 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.