我一直在尝试制作一个正则表达式,可以检测出表情符号是否是国旗。我希望regex能匹配所有国旗(从阿森松岛到津巴布韦)。
我的方法是把所有的国旗一个接一个地放在regex中。我希望有人能教我更好的方法。
最佳答案
要保持regex的精确性,只能构建regex范围。
var country_emoji_ranges = ['\\u{1F1E6}[\\u{1F1E9}-\\u{1F1EC}\\u{1F1EE}\\u{1F1F1}\\u{1F1F2}\\u{1F1F4}\\u{1F1F6}-\\u{1F1FA}\\u{1F1FC}\\u{1F1FD}\\u{1F1FF}]',
'\\u{1F1E7}[\\u{1F1E6}\\u{1F1E7}\\u{1F1E9}-\\u{1F1EF}\\u{1F1F1}-\\u{1F1F4}\\u{1F1F6}-\\u{1F1F9}\\u{1F1FB}\\u{1F1FC}\\u{1F1FE}\\u{1F1FF}]',
'\\u{1F1E8}[\\u{1F1E6}\\u{1F1E8}\\u{1F1E9}\\u{1F1EB}-\\u{1F1EE}\\u{1F1F0}-\\u{1F1F4}\\u{1F1F7}\\u{1F1FA}-\\u{1F1FF}]',
'\\u{1F1E9}[\\u{1F1EA}\\u{1F1EF}\\u{1F1F0}\\u{1F1F2}\\u{1F1F4}\\u{1F1FF}]',
'\\u{1F1EA}[\\u{1F1E8}\\u{1F1EA}\\u{1F1EC}\\u{1F1ED}\\u{1F1F7}-\\u{1F1F9}]',
'\\u{1F1EB}[\\u{1F1EE}\\u{1F1EF}\\u{1F1F0}\\u{1F1F2}\\u{1F1F4}\\u{1F1F7}]',
'\\u{1F1EC}[\\u{1F1E6}\\u{1F1E7}\\u{1F1E9}-\\u{1F1EE}\\u{1F1F1}-\\u{1F1F3}\\u{1F1F5}-\\u{1F1FA}\\u{1F1FC}\\u{1F1FE}]',
'\\u{1F1ED}[\\u{1F1F0}\\u{1F1F2}\\u{1F1F3}\\u{1F1F7}\\u{1F1F9}\\u{1F1FA}]',
'\\u{1F1EE}[\\u{1F1E9}-\\u{1F1F4}\\u{1F1F6}-\\u{1F1F9}]',
'\\u{1F1EF}[\\u{1F1EA}\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1F8}\u{1F1F7}, \u{1F1F8}\u{1F1F8}, \u{1F1F8}\u{1F1F9}, \u{1F1F8}\u{1F1FB}, \u{1F1F8}\u{1F1FD}, \u{1F1F8}\u{1F1FE}, \u{1F1F8}\u{1F1FF}, \u{1F1F9}\u{1F1E8}, \u{1F1F9}\u{1F1E9}, \u{1F1F9}\u{1F1EB}, \u{1F1F9}\u{1F1EC}, \u{1F1F9}\u{1F1ED}, \u{1F1F9}\u{1F1EF}, \u{1F1F9}\u{1F1F0}, \u{1F1F9}\u{1F1F1}, \u{1F1F9}\u{1F1F2}, \u{1F1F9}\u{1F1F3}, \u{1F1F9}\u{1F1F4}, \u{1F1F9}\u{1F1F7}, \u{1F1F9}\u{1F1F9}, \u{1F1F9}\u{1F1FB}, \u{1F1F9}\u{1F1FC}, \u{1F1F9}\u{1F1FF}, \u{1F1FA}\u{1F1E6}, \u{1F1FA}\u{1F1EC}, \u{1F1FA}\u{1F1F2}, \u{1F1FA}\u{1F1F8}, \u{1F1FA}\u{1F1FE}, \u{1F1FA}\u{1F1FF}, \u{1F1FB}\u{1F1E6}, \u{1F1FB}\u{1F1E8}, \u{1F1FB}\u{1F1EA}, \u{1F1FB}\u{1F1EC}, \u{1F1FB}\u{1F1EE}, \u{1F1FB}\u{1F1F3}, \u{1F1FB}\u{1F1FA}, \u{1F1FC}\u{1F1EB}, \u{1F1FC}\u{1F1F8}, \u{1F1FE}\u{1F1EA}, \u{1F1FE}\u{1F1F9}, \u{1F1FF}\u{1F1E6}, \u{1F1FF}\u{1F1F2}, \u{1F1FF}\u{1F1FC}";
console.log(text.match(country_emoji_rx).length);
如果您想匹配不支持
u
标志的js环境中的那些标志,可以使用transpiled版本:/(?:\uD83C\uDDE6)(?:\uD83C[\uDDE9-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|(?:\uD83C\uDDE7)(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uD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