regex 使用正则表达式检测表情符号是否为国旗

hrysbysz  于 2023-03-20  发布在  其他
关注(0)|答案(4)|浏览(354)

我一直在尝试做一个正则表达式,它可以检测一个表情符号是否是一个国家的国旗。我希望正则表达式匹配所有国家的国旗(从🇦🇨Ascension,🇿🇼津巴布韦)。
我的方法是把所有的国旗一个接一个地放到正则表达式中,我希望有人能告诉我一个更好的方法。

fhg3lkii

fhg3lkii1#

一个国旗表情符号对应一对本地符号(两个字母)来标识国家(例如FR代表法国-see list)。你可以使用一个正则表达式来匹配这些字母的任意组合。当然,这将包括不存在的国家代码(例如ZZ),但这应该排除任何其他表情符号。
这就是:

var reg = /[\uD83C][\uDDE6-\uDDFF][\uD83C][\uDDE6-\uDDFF]/;
reg.test("😀"); // false
reg.test("🇦🇨"); // true
6l7fqoea

6l7fqoea2#

由于标志基本上是由两个Unicode字符创建的,因此可能的选项是str.match(/[🇦-🇿]{2}/u)(假定str包含字符串)。范围表达式中的两个值是U+1F1E6(区域指示符符号字母A)和U+1F1FF(区域指示符符号字母Z),这两个值都是从Unicode 6.0开始提供的。
这种解决方案的主要缺点是它匹配那些指示符符号的所有可能组合的事实,因此不能保证指示符代表有效的国家,例如🇦🇦将被匹配以及🇦🇨。

tp5buhyn

tp5buhyn3#

为了保持正则表达式的精确性,您只能构建正则表达式范围。

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{1F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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-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|(?:\uD83C\uDDE8)(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF4\uDDF7\uDDFA-\uDDFF])|(?:\uD83C\uDDE9)(?:\uD83C[\uDDEA\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|(?:\uD83C\uDDEA)(?:\uD83C[\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDF9])|(?:\uD83C\uDDEB)(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|(?:\uD83C\uDDEC)(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|(?:\uD83C\uDDED)(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\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uDDE6\uDDF2\uDDFC])/g
p5fdfcr1

p5fdfcr14#

const regex = /^((?![\p{Regional_Indicator}]).)*$/u;
regex.test("country_flag_emoji"); // false

相关问题