Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Regex replace

I am boggled by regex I think I'm dyslexic when it comes to these horrible bits of code.. anyway, there must be an easier way to do this- (ie. list a set of replace instances in one line), anyone? Thanks in advance.

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;
}
like image 826
Inigo Avatar asked Nov 26 '10 13:11

Inigo


People also ask

How do I replace multiple characters in a string?

Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

Can I use regex in replace?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true: If the replacement string cannot readily be specified by a regular expression replacement pattern.

What is regex replace in C#?

Replace. This C# method processes text replacements. It handles simple and complex replacements. For complex patterns, we use a MatchEvaluator delegate to encode the logic.


3 Answers

You could use a function replacement. For each match, the function decides what it should be replaced with.

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-@";
        }
    });
}
like image 181
Markus Jarderot Avatar answered Oct 11 '22 06:10

Markus Jarderot


You can define either a generic function, which would make sense if you can reuse it in more parts of your code, thus making it DRY. If you don't have reason to define a generic one, I would compress only the part which cleans sequences and leave the other replaces as they are.

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;
}

But be careful, the order of the replacements were changed it in this code.. although it seems they might not affect the result.

like image 25
fifigyuri Avatar answered Oct 11 '22 07:10

fifigyuri


You could do it like this:

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;
}

Keep in mind that the order of object properties is not reliably determinable (but most implementations will return them in order of definition). You will probably need multiple constructs like this if you need to ensure a specific order.

like image 33
jwueller Avatar answered Oct 11 '22 06:10

jwueller