Reputation: 2504
I have an NSString
and would like to check if a given character at a certain index is an emoji.
However, there doesn't seem to be any reliable way to create an NSCharacterSet
of emoji characters, since they change from iOS update to update. And a lot of the available solutions rely on Swift features such as UnicodeScalar
. All solutions seem to involve hardcoding the codepoint values for emojis.
As such, is it possible to check for emojis at all?
Upvotes: 0
Views: 1452
Reputation: 90551
It's a bit of a complicated question because Unicode is complicated, but you can use NSRegularExpression
to do this:
NSString *s = @"where's the emoji 😎 ?";
NSRegularExpression *r = [NSRegularExpression regularExpressionWithPattern:@"\\p{Emoji_Presentation}" options:0 error:NULL];
NSRange range = [r rangeOfFirstMatchInString:s options:0 range:NSMakeRange(0, s.length)];
NSLog(@"location %lu length %lu", (unsigned long)range.location, (unsigned long)range.length);
produces:
2019-01-16 18:07:42.629 emoji[50405:6837084] location 18 length 2
I'm using the \p{Unicode property name}
pattern to match characters which have the specified Unicode property. I'm using the property Emoji_Presentation
to get those character which present as Emoji by default. You should review Unicode® Technical Standard #51 — Annex A: Emoji Properties and Data Files and the data files linked in A.1 to decide which property you actually care about.
Upvotes: 3