【问题标题】:Regex to find emoji names with colon and skintone正则表达式查找带有冒号和肤色的表情符号名称
【发布时间】:2018-12-21 20:03:57
【问题描述】:

我的解析器使用EmojiMart

我见过这个related question,但它似乎与我的不同。

所以我需要返回表情符号名称或 :code: 以便他们能够对其进行解码。

例如,我有这样的文字:

:+1::skin-tone-6::man-pouting:Hello world:skin-tone- 
6:lalalalla:person_with_pouting_face: :poop::skin-tone-11: mamamia 
:smile: :skin-tone-6:

它应该匹配整个:+1::skin-tone-6: 而不是单独的:+1::skin-tone-6:: - 仅当它们之间没有空格时。 (注意:smile::skin-tone-6: 之间的空格)

条件:

如果肤色是 2-6,它应该只匹配 :code::skintone:

如果我这样做 str.split(regex) 这是我的预期结果(数组):

- :+1::skin-tone-6:
- :man-pouting:
- Hello world
- :skin-tone-6:
- lalalalla
- :person_with_pouting_face: 
- :poop:
- :skin-tone-11: 
-  mamamia 
- :smile: 
- :skin-tone-6:

【问题讨论】:

    标签: javascript arrays regex emoji emoji-tones


    【解决方案1】:

    您可以使用String#split()

    /(:[^\s:]+(?:::skin-tone-[2-6])?:)/
    

    正则表达式。请参阅regex demo

    详情

    • : - 冒号
    • [^\s:]+ - 除空格和: 之外的 1+ 个字符
    • (?:::skin-tone-[2-6])? - 可选序列
      • ::skin-tone- - 文字子字符串
      • [2-6] - 一个从 26 的数字
    • : - 冒号。

    JS 演示:

    var s = ":+1::skin-tone-6::man-pouting:Hello world:skin-tone-6:lalalalla:person_with_pouting_face: :poop::skin-tone-11: mamamia :smile: :skin-tone-6:";
    var reg = /(:[^\s:]+(?:::skin-tone-[2-6])?:)/;
    console.log(s.split(reg).filter(x => x.trim().length !=0 ));

    .filter(x => x.trim().length !=0 ) 从结果数组中删除所有空白项。对于 ES5 及更早版本,请使用 .filter(function(x) { return x.trim().length != 0; })

    【讨论】:

    • 谢谢您的好先生。我想知道我是否也可以在str.replace(regex, callback) 上做到这一点。现在我正在做str.split(regex).filter(Boolean).map(emoji => myfunction).join('') 只是为了模仿替换的作用。但我认为替换要快得多。
    • @IamL 你需要用其他东西替换它们吗?是的,.replace(reg, function(match) { return myfunction(match); }) 之类的东西会起作用。
    • 是的,但是替换只会用:+1::skin-tone-6: 替换那个。它与其他 :code: 不“匹配”(没有肤色)。我想我必须使用 split 代替?
    • @IamL 输入字符串的预期结果是什么?
    • @IamL :) 忘记了全局修饰符 updated fiddle。当您在 split() 方法中使用正则表达式时,默认行为是查找要拆分的所有匹配项。在.replace 中,应该明确定义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 2013-05-04
    相关资源
    最近更新 更多