Search code examples
javascriptregexregex-greedy

Javascript RegEx Lazy match


I am trying to find for loop pattern in javascript code, and replace syntax (from : to in), using below regex way,

var str="for(var x in []) for(var y in [])";

str.replace( new RegExp( '(for\\s*\\(.+\\s+):(\\s+.+\\))', 'ig' ), "\$1in\$2" )

i.e.

for(var x : list)
{
 // something
}

with

for(var x in list)
{
 // something
}

However I am facing issues when there are multiple for loops in same line.

for(var x : list) { for(var y : list) {
     // something
 }
}

which is valid syntax, however due to Greedy regex approach it converts as below:

for(var x : list) { for(var y in list) {
         // something
 }
}

I tried to explore lazy regex syntax but couldn't make it work. How can I achieve this ?


Solution

  • You could add some lazy quantifiers to all * and +. and take for as part of the replacement, because of matching.

    var str = "for(var x : []) for(var y : [])";
    
    console.log(str.replace(/for\s*?(\(.+?\s+?):(\s+?.+?\))/ig, "for $1in$2"));

    A bit shorter and it includes for in the first group.

    var str = "for(var x : []) for(var y : [])";
    
    console.log(str.replace(/(for\s*?\(.+?):(.+?\))/ig, "$1in$2"));