Search code examples
javascriptregexregex-groupregex-greedy

RegEx for replacing everthing and new lines in between two words


I am looking for a javascript regex for deleting all lines between two words including the words. I could find something like this

Dim input = "one two three four START four five four five six END seven"
Dim output = Regex.Replace(input, "(?<=START.*)four(?=.*END)", "test")

This is for VB and in addition, it does not work for multiple lines and also delete both start and end.

How do I solve this problem?


Solution

  • This expression can capture your undesired text in between start and end including new lines:

    START([\s\S]*)END
    

    enter image description here

    RegEx Descriptive Graph

    This graph visualizes the expression, and if you want, you can test other expressions in this link:

    enter image description here

    Basic Performance Test

    This JavaScript snippet returns runtime of a 1-million times for loop for performance. You could simply remove the for and that might be what you may be looking for:

    const repeat = 1000000;
    const start = Date.now();
    
    for (var i = repeat; i >= 0; i--) {
    	const string = 'anything you wish before START four five four \n \n \n \n five six END anything you wish after';
    	const regex = /(.*START)([\s\S]*)(.*END)/gm;
    	var match = string.replace(regex, "$1 $3");
    }
    
    const end = Date.now() - start;
    console.log("YAAAY! \"" + match + "\" is a match 💚💚💚 ");
    console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");

    Edit

    If you wish to replace one word in a string with new lines, this expression might be helpful:

    enter image description here