Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression except [Value]

Tags:

I have a String and want to replace it with other String as given in mssqlFunctions object.

var mssqlFunctions = {
                DateDiff: "DATEDIFF",
                Abs: "ABS",
                y: 'year',
                m: 'minute'
            };

My String is: DateDiff(m, Abs(23)[Emy()])

This is my code to replace String

var regularExpression = new RegExp(Object.keys(mssqlFunctions).join("|"),"gi");

formula = formula.replace(regularExpression, function(matched){
  return mssqlFunctions[matched];
});

So it gives Output as DATEDIFF(minute, ABS(23)[Eminuteyear()])

But I don't want to replace string which is in []

So the Output which I want is

DATEDIFF(minute, ABS(23)[Emy()])

like image 205
Vishesh Avatar asked Oct 22 '18 16:10

Vishesh


1 Answers

You may match and capture a string between square brackets and check if the group matched. If the group matched, the match should fail, and you need to replace with the whole match (to put it back). Else, you may replace with the modified value.

Use

var formula = "DateDiff(m, Abs(23)[Emy()])";
var mssqlFunctions = {
    DateDiff: "DATEDIFF",
    Abs: "ABS",
    y: 'year',
    m: 'minute'
};
var regularExpression = new RegExp("(\\[[^\\][]*])|" + Object.keys(mssqlFunctions).join("|"),"gi");

formula = formula.replace(regularExpression, function(matched, group1){
  return group1 ? matched : mssqlFunctions[matched];
});
console.log(formula); // => DATEDIFF(minute, ABS(23)[Emy()])

The (\\[[^\\][]*])| is the added regex alternative branch. It matches and captures

  • \\[ - a [
  • [^\\][]* - 0+ chars other than [ asnd ]
  • ] - a ] char.

The matched variable stands for the whole match, group1 stands for Group 1 match. The return group1 ? matched : mssqlFunctions[matched]; part checks if group1 matches, and if yes, matched is used to replace the match, else mssqlFunctions[matched].

If you wonder why double backslashes are used, see Why do regex constructors need to be double escaped?.

like image 148
Wiktor Stribiżew Avatar answered Sep 23 '22 07:09

Wiktor Stribiżew