簡體   English   中英

正則表達式匹配各種表情符號的列表

[英]Regex matching list of emoticons of various type

我需要創建一個功能,這將允許我解析文本以尋找不同格式的圖釋字符串的匹配項。 它可以是:)類型的圖釋,也可以是&lt;dog&gt; <dog> )類型。 目前,我的函數可以找到這兩種類型,但是需要兩個不同的正則表達式來完成此任務,我想一步就完成。 有任何想法嗎 ?

jsfiddle的實時示例: http : //jsfiddle.net/rmQSx/5/

和代碼:

function replaceEmoticons(text) {
    var emots1 = {
        ':)': 'smile.gif',
        ':(': 'sad.gif',
    },
    emots2 = {
        '&lt;dog&gt;': 'dog.gif',
        '&lt;fly&gt;': 'fly.gif'   
    },
    regex1,regex2,p,re;


    for(p in emots1){
        regex1 = "["+p+"]{2}";
        re = new RegExp(regex1, "g");

        text = text.replace(re, function (match) {
            return typeof emots1[match] != 'undefined' ?
                '<img src="'+emots1[match]+'"/>' :
                match;
        });
    }

    for(p in emots2){
        regex2 = "("+p+")(|$)";
        re = new RegExp(regex2, "g");

        text = text.replace(re, function(match) {
            return typeof emots2[match] != 'undefined' ?
                '<img src="'+emots2[match]+'"/>' :
                match;
        });
    }

     return text;   
}

console.log(replaceEmoticons('this is &lt;dog&gt;b a&lt;fly&gt; simple test :) , ;)   and more:):('));

我很確定您不需要在每個for循環開始時所做的有趣的事情來修改正則表達式。 擺脫它,沒有什么可以阻止您將這兩個集合合並在一起。

但是,制作正則表達式時,您應該在笑臉中轉義特殊字符() 另外,我建議使正則表達式搜索不區分大小寫,以使<dog><DOG>都匹配。

//helper function to escape special characters in regex
function RegExpEscape(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); 
}

function replaceEmoticons(text) {   
    var emots = {
        ':)'         : 'smile.gif',
        ':('         : 'sad.gif',
        '&lt;dog&gt;': 'dog.gif',
        '&lt;fly&gt;': 'fly.gif'
    }

    var result = text;
    var emotcode;
    var regex;

    for (emotcode in emots)
    {
        regex = new RegExp(RegExpEscape(emotcode), 'gi');
        result = result.replace(regex, function(match) {
            var pic = emots[match.toLowerCase()];

            if (pic != undefined) {
                return '<img src="' + pic + '"/>';
                    } else {
                return match;
                    }
                });
    }

    return result;    
}

使用|

你可以這樣做:

re = new RegExp(smiley1|smiley2|...|smileyN);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM