javascriptregexcss-parsing

Replace content that is between to comments


I would like to replace the content that is between two comments like

/**** Useless CSS ****/
.my-class{
 margin: 12px;
}

/* Several Lines after including other comments **/

/**** END Useless CSS ****/

.other {
 padding: 12px;
}
/* Hello */

So far I have:

[\/* Useless CSS \*\/](.|[\r\n])*?END Useless CSS \*\*\*\*\/?

But this doesn't work. I got an error in Regex101: Catastrophic backtracking


Solution

  • Part of your issue is the first part of your regex. You're using [\/* Useless CSS \*\/], a character class, which means any character in this set. In other words any of the following characters (after removing duplicate letters): /* UselCS. That's definitely not your intention, but that's what it's doing. The code below removes the character class from the pattern so that it matches /**** Useless CSS ****/ explicitly.

    The second change is turning (.|[\r\n])*? into [\s\S]*?. There's no need to have regex check against two options each time. If it's a set of characters, just add them to the same character class. [\s\S] is a way of representing any character (including the newline character). Another way (works in JavaScript, but not many other regex engines) is to use [^].

    The third change was changing \*\*\*\* to \*{4}. Not only is this shorter and easier to understand, it also improves performance because the regex engine doesn't need to go token by token \*, then \*, then \*, etc. It's told to match * four times, so it does it in one go instead of 4. This means that \*\*\*\* takes four steps while \*{4} only takes one.

    You may also append \s* to the end to remove additional whitespace.

    \/\*{4} Useless CSS \*{4}\/[\s\S]*?\/\*{4} END Useless CSS \*{4}\/
    

    var s = `/**** Useless CSS ****/
    .my-class{
     margin: 12px;
    }
    
    /* Several Lines after including other comments **/
    
    /**** END Useless CSS ****/
    
    .other {
     padding: 12px;
    }
    /* Hello */`
    var r = /\/\*{4} Useless CSS \*{4}\/[\s\S]*?\/\*{4} END Useless CSS \*{4}\//gi
    
    console.log(s.replace(r, ''))