1

My regex must match what's within /* @DT-HIDE / and / @/DT-HIDE */. It's fine until a page contains two blocks.

If there are two blocks, well, $1 will match all that's between the first opening @DT-HIDE and last @/DT-HIDE. I suppose it's about a greedy * instead of an ? but I can't figure it out.

Regex:

const pattern = new RegExp(/(\/\*\s@DT-HIDE\s\*\/) ([\s\S]*?) (\/\*\s@\/DT-HIDE\s\*\/)/g);

Example value being processed:

/* @DT-HIDE */
function(){
    return "...";
}
/* @/DT-HIDE */

/* @DT-HIDE */
function logic(url){
    return new Promise( (resolve, reject) => {
        ...
    });
}
/* @/DT-HIDE */
5
  • 1
    Since you're using the new RegExp() constructor, it's a shame you don't pass it a string rather than a /.../ construct : you would avoid having to escape slashes inside the regexp. You would instead need to escape double-quotes, which wouldn't be a problem in your case. Commented May 30, 2017 at 15:34
  • Well, that's already a good info - thanks for that! Commented May 30, 2017 at 15:35
  • 3
    Hah.. As I can see the only problem are the two spaces you have between the groups (between the brackets): /(\/\*\s@DT-HIDE\s\*\/)([\s\S]*?)(\/\*\s@\/DT-HIDE\s\*\/)/g. Also you don't need the constructor simply assign the regex to the pattern variable Commented May 30, 2017 at 15:36
  • @Aaron: double (or single) quotes but also all backslashes. Commented May 30, 2017 at 16:35
  • @CasimiretHippolyte right, although they already need to be escaped in /.../ constructs Commented May 30, 2017 at 21:23

1 Answer 1

1

You should have had [\s\S]* in your original pattern, otherwise you would not obtain a "greedy" match.

However, as Slim noticed, the spaces you introduced failed the match since there is no space after /* @DT-HIDE */. So, you may solve the issue by removing the spaces. Declaring the pattern with a conbstructor notation is a good idea when your pattern contains many slashes, but in this case you may use a regex literal without the RegExp constructor:

const pattern = /(\/\*\s@DT-HIDE\s\*\/)([\s\S]*?)(\/\*\s@\/DT-HIDE\s\*\/)/g;

However, the pattern is not optimal, since the lazy dot matching patterns may involve many "forward-trackin" steps. I suggest unrolling it as

const pattern = /(\/\*\s@DT-HIDE\s\*\/)([^\/]*(?:\/(?!\*\s@\/DT-HIDE\s\*\/)[^\/]*)*)(\/\*\s@\/DT-HIDE\s\*\/)/g;
                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

See the regex demo.

The [^\/]*(?:\/(?!\*\s@\/DT-HIDE\s\*\/)[^\/]*)* will make matching more efficient especially if the number of / is not that big in between the delimiters.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.