How to add emojis to alphanumerics RegEx in Python

Viewed 53

How can one add all emojis to alphanumerics in the RegEx, like this

pattern = r'\w+'
1 Answers

You can use the emoji package (pip install emoji) to get the emoji set and combine it with \w+ in this way: (?:\w|<emoji_pattern>)+:

from emoji import UNICODE_EMOJI
import re

e_list = UNICODE_EMOJI.keys()
word_emoji_rx = re.compile(r"(?:\w|{})+".format("|".join(map(re.escape, sorted(e_list,key=len,reverse=True)))))
print(word_emoji_rx.findall(r'abc def ghi'))
# => ['abc', 'def', 'ghi']

See a Python demo

Related