【问题标题】:Assess if a c# string is a single Emoji OR an Emoji ZWJ Sequence?评估 c# 字符串是单个 Emoji 还是 Emoji ZWJ 序列?
【发布时间】:2020-11-25 17:37:02
【问题描述】:

有什么方法可以判断 c# string 是单个 Emoji 还是有效的 Emoji ZWJ 序列?

我希望基本上能够从官方 unicode 列表中找到任何 Emoji,http://www.unicode.org/reports/tr51/tr51-15.html#emoji_data

我似乎没有为此找到一个 nuget 包,而且大多数 SO 问题似乎并不容易适用于我的案例(即Is there a way to check if a string in JS is one single emoji?

【问题讨论】:

  • 将所有表情符号字符值存储在 HashSet 中,然后在文本中查找匹配项。希望它不会是一个巨大的字符串,而更像是一个注释类型的东西。
  • 这听起来很难维护,但我想这会奏效。
  • “维护困难”:只需从问题中的链接下载列表即可。
  • 这适用于今天,但需要特别注意以后更新文档。
  • 也许这个答案 (stackoverflow.com/questions/51502486/…) 会有所帮助

标签: c# emoji


【解决方案1】:

我最终使用了 Unicode 正则表达式,它在 .NET 中部分实现。 使用这个问题(C# - Regular expression to find a surrogate pair of a unicode codepoint from any string?),我想出了以下问题。

正则表达式

//Returns the Emoji
@"([\uD800-\uDBFF][\uDC00-\uDFFF]\p{M}*){1,5}|\p{So}"

//Returns true if the string is a single Emoji
@"^(?>(?>[\uD800-\uDBFF][\uDC00-\uDFFF]\p{M}*){1,5}|\p{So})$"

测试

    public class EmojiTests
    {
        private static readonly Regex IsEmoji = new Regex(@"^(?>(?>[\uD800-\uDBFF][\uDC00-\uDFFF]\p{M}*){1,5}|\p{So})$", RegexOptions.Compiled);

        [Theory]
        [InlineData("⭐")]
        [InlineData("?")]
        [InlineData("?")]
        [InlineData("?")]
        [InlineData("??")]
        [InlineData("?")]//pinched fingers, coming soon :p
        public void ValidEmojiCases(string input)
        {
            Assert.Matches(IsEmoji, input);
        }

        [Theory]
        [InlineData("")]
        [InlineData(":p")]
        [InlineData("a")]
        [InlineData("<")]
        [InlineData("⭐⭐")]
        [InlineData("?a")]
        [InlineData("‼️")]
        [InlineData("↔️")]
        public void InvalidEmojiCases(string input)
        {
            Assert.DoesNotMatch(IsEmoji, input);
        }
    }

它并不完美(即“™️”返回 true,“◻️”返回 false),但可以。

【讨论】:

    猜你喜欢
    • 2018-11-16
    • 2019-01-12
    • 2022-01-07
    • 2016-09-20
    • 2019-04-01
    • 2015-09-25
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    相关资源
    最近更新 更多