Aravind Karthik
Aravind Karthik

Reputation: 33

How do I extract emojis from a string in Flutter?

I need to extract emojis from a string for this side project I am working on in Flutter

Input: "Hey everyone 🥺🥺🥺"

Output: "🥺🥺🥺"

How do I achieve this?

This is what I have tried so far based on this post

var emojiRegex = RegExp(
  "r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])'");

getEmojis(String message) {
  print("EXTRACTING EMOJI");
  var output = message.replaceAll(emojiRegex,"");
  print("EMOJI: $output");
}

Upvotes: 2

Views: 1269

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627334

You can use

String extractEmojis(String text) {
  RegExp rx = RegExp(r'[\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\u{1F9B0}-\u{1F9B3}]', unicode: true);
  return rx.allMatches(text).map((z) => z.group(0)).toList().join(""); 
}

void main() {
    print(extractEmojis("Hey everyone 🥺🥺🥺"));
}

Output: 🥺🥺🥺

The [\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\u{1F9B0}-\u{1F9B3}] regex is taken from Why do Unicode emoji property escapes match numbers? and it matches emojis proper and light skin to dark skin mode chars and red-haired to white-haired chars.

Upvotes: 4

Related Questions