I wrote the regular new RegExp('(<%--)(.*)(--%>)','gim') regular new RegExp('(<%--)(.*)(--%>)','gim') , which should find everything that is enclosed in a sequence of <%-- --%> characters. It works fine within one line, but if there is a line break between the <%-- --%> character sequences, then everything will break. I decided to catch line breaks in such a regular way: (<%--)([\s\S]*)(--%>) , but it does not work correctly.

Tell me, how to write the regularity which will take into account the line breaks?

  • but it does not work correctly - namely? - Alexey Ten
  • line break, this is \ n (either \ r or \ n \ r) - Stanislav
  • @AlexeyTen test here: regex101.com - understand what the joint is - sanu0074
  • Hello, do you need help or me? - Alexey Ten
  • @Stanislav I understand this, just like [\ s \ S] * will look for them, but ... does not work - sanu0074

2 answers 2

https://regex101.com/r/cZ6oI8/3

 var re = /(<%--)([\s\S]*?)(--%>)/g; 

By default, the quantifier * “greedy” and tries to capture as many characters as possible. To limit his greed you need to add a flag to it ? (not to be confused with a quantifier ? ).

  • You see, it was nevertheless clear to you in the question, and what were your comments about ticks .... - sanu0074
  • @ sanu0074 Nowhere in the question is there an example of text and the knowledge that there may be more than one such blocks. Learn to ask questions correctly, and when they ask you for details, let them, rather than stand in a pose. - Alexey Ten
  • I gave a link with an example, indicated what should look for, how it works like no. The error will highlight you regex101.com. You just were not attentive. You should not be nervous and show ignorance, because it does not make sense and no one will be better off by this - sanu0074
  • one
    You gave the link in the seventh comment, but you should have been at the very beginning and in general in the post. - Alexey Ten

I recommend to try this (for those who encounter):

 new RegExp('(<%--)((?:.|\n)*?)(--%>)','g') 

I personally did not search using [\s\S]*? (debazhil in chrome console), despite the fact that in all references it is indicated as the most correct, as well as on resources where regular expressions are usually tested - such as regex101.com, jsfiddle.net - everything works.

Ideally, both methods should work (according to the logic of things):

([\s\S]*?) - because \ s is any whitespace character (including tabs and translations), and \ S is any character except whitespace.

((?:.|\n)*?) - because . - any character except the line break, \n - the line break itself. more difficult to read ("non-capturing brackets" are used), but more reliable

More about RegExp