代码之家  ›  专栏  ›  技术社区  ›  Inigo

多正则表达式替换

  •  15
  • Inigo  · 技术社区  · 14 年前

    我被ReGEX弄糊涂了,我觉得当我遇到这些可怕的代码时,我是读错了。无论如何,必须有一个更简单的方法来做到这一点(即在一行中列出一组替换实例),有人吗?提前谢谢。

    function clean(string) {
        string = string.replace(/\@~rb~@/g, '').replace(/}/g, '@~rb~@');
        string = string.replace(/\@~lb~@/g, '').replace(/{/g, '@~lb~@');
        string = string.replace(/\@~qu~@/g, '').replace(/\"/g, '@~qu~@');
        string = string.replace(/\@~cn~@/g, '').replace(/\:/g, '@~cn~@');
        string = string.replace(/\@-cm-@/g, '').replace(/\,/g, '@-cm-@');
        return string;
    }
    
    5 回复  |  直到 11 年前
        1
  •  14
  •   fifigyuri    14 年前

    您可以定义任意一个泛型函数,如果您可以在代码的更多部分中重用它,从而使它变干,这将是有意义的。如果你没有理由定义一个通用的,我只压缩清理序列的部分,而保留其他替换部分。

    function clean(string) {
        string = string.replace(/\@~rb~@|\@~lb~@|\@~qu~@|\@~cn~@|\@-cm-@/g, '')
          .replace(/}/g, '@~rb~@').replace(/{/g, '@~lb~@')
          .replace(/\"/g, '@~qu~@').replace(/\:/g, '@~cn~@')
          .replace(/\,/g, '@-cm-@');
        return string;
    }
    

    但是要小心,替换的顺序在这段代码中被改变了。。尽管 似乎 它们可能不会影响结果。

        2
  •  33
  •   Markus Jarderot    12 年前

    您可以使用函数替换。对于每一个匹配项,函数决定应该用什么替换它。

    function clean(string) {
        // All your regexps combined into one:
        var re = /@(~lb~|~rb~|~qu~|~cn~|-cm-)@|([{}":,])/g;
    
        return string.replace(re, function(match,tag,char) {
            // The arguments are:
            // 1: The whole match (string)
            // 2..n+1: The captures (string or undefined)
            // n+2: Starting position of match (0 = start)
            // n+3: The subject string.
            // (n = number of capture groups)
    
            if (tag !== undefined) {
                // We matched a tag. Replace with an empty string
                return "";
            }
    
            // Otherwise we matched a char. Replace with corresponding tag.
            switch (char) {
                case '{': return "@~lb~@";
                case '}': return "@~rb~@";
                case '"': return "@~qu~@";
                case ':': return "@~cn~@";
                case ',': return "@-cm-@";
            }
        });
    }
    
        3
  •  0
  •   jwueller    14 年前

    你可以这样做:

    function clean(str) {
        var expressions = {
            '@~rb~@': '',
            '}':      '@~rb~@',
            // ...
        };
    
        for (var key in expressions) {
            if (expressions.hasOwnProperty(key)) {
                str = str.replace(new RegExp(key, 'g'), expressions[key]);
            }
        }
    
        return str;
    }
    

    请记住,对象属性的顺序不可可靠地确定(但大多数实现将按照定义的顺序返回它们)。如果需要确保一个特定的顺序,您可能需要这样的多个构造。

        4
  •  0
  •   Stephen    14 年前

    你可以把它们按顺序拴起来。

    function clean(string) {
        return string.replace(/\@~rb~@/g, '').replace(/}/g, '@~rb~@')
                     .replace(/\@~lb~@/g, '').replace(/{/g, '@~lb~@')
                     .replace(/\@~qu~@/g, '').replace(/\"/g, '@~qu~@')
                     .replace(/\@~cn~@/g, '').replace(/\:/g, '@~cn~@')
                     .replace(/\@-cm-@/g, '').replace(/\,/g, '@-cm-@');
    }
    
        5
  •  0
  •   Jonny Buchanan    14 年前

    …一定有更简单的方法 这个(即列出一组替换 一行中的实例。。。

    百胜,API第一思想。怎么样。。。?

    var clean = multiReplacer({
        "@~rb~@": "",
        "@~lb~@": "",
        "@~qu~@": "",
        "@~cn~@": "",
        "@-cm-@": "",
        "}": "@~rb~@",
        "{": "@~lb~@",
        "\\": "@~qu~@",
        ":": "@~cn~@",
        ",": "@-cm-@"
    });
    

    管道工程:

    // From http://simonwillison.net/2006/Jan/20/escape/
    RegExp.escape = function(text)
    {
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    };
    
    function multiReplacer(replacements)
    {
        var regExpParts = [];
        for (prop in replacements)
        {
            if (replacements.hasOwnProperty(prop))
            {
                regExpParts.push(RegExp.escape(prop));
            }
        }
    
        var regExp = new RegExp(regExpParts.join("|"), 'g');
        var replacer = function(match)
        {
            return replacements[match];
        };
    
        return function(text)
        {
            return text.replace(regExp, replacer);
        };
    }