在javascript中使用正则表达式检测表情符号 [英] Detecting emoticons with regex in javascript

查看:249
本文介绍了在javascript中使用正则表达式检测表情符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个用于检测表情符号的类,并使用以下内容来检测:)表情符号,包括各种变体( =],=), [=,[:,等),但它不起作用,我不能为我的生活弄清楚出了什么问题。我正在JSFiddle中测试它。

I am creating a class to detect emoticons and have the following to detect :) smilies including their various variations (=], =), [=, [:, etc.), but it doesn't work and I can't for the life of me figure out what is wrong. I'm testing it in JSFiddle.

var DetectEmoticons = {
    countHappy: function(data) {
        var pattern = new RegExp("[:/=]-?[]/)] | [[/(]-?[:/=]", "g");
        var count = (data.match(pattern) || []).length;
        return count;
    }
}
alert(DetectEmoticons.countHappy("=)"));


推荐答案

[:=;] ? - [)(| \\ / \] \ [] | [)(| \\ / \] \ [] - [:=;]

这看起来像是一个糟透人的混乱,直到你打破它:

This looks like an unholy mess from hell until you break it down:

[ :=;] 匹配一个:或一个=或一个;

[:=;] matches one : or one = or one ;

[)(| \\ / \] \ [] 匹配一个),(,|,\(反斜杠,因为它是一个元字符),/,](反斜杠,因为它是元字符)或[(反斜杠,因为它)是一个元字符。)(我们不需要反斜杠)或(因为它们不是字符类中的元字符)。

[)(|\\/\]\[] matches one ), (, |, \ (backslashed because it is a metacharacter), /, ] (backslashed because it is a metacharacter) or [ (backslashed because it is a metacharacter). (We didn't need to backslash ) or ( because they are not metacharacters inside of a character class).

| 在中心意味着'匹配我的左边或匹配我的权利'然后我写相同的两个字符类但反过来匹配方向相反的表情符号。

The | in the center means 'match left of me OR match right of me' and then I write the same two character classes but in reverse to match smileys that are reversed in direction.

我认为您的正则表达式的问题在于:

I think the problem with your regex is here:

[] /)]

你忘记了scape第一个] ,带有 \ ,因此它被视为提前结束字符类。

You forgot to escape the first ] with a \ so it is treated as ending the character class prematurely.

另一个问题是你认为正斜杠 / 用于逃避。不是, \ 用于转义, / 在正则表达式中没有特殊含义。

The other problem is that you thought forward slash / is used to escape. It's not, \ is used to escape, / has no special meaning in regex.

这篇关于在javascript中使用正则表达式检测表情符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆