en.javascript.info/10-regular-expressions-javascript/8-regexp-greedy-and-lazy/3-find-html-comments/solution.md
2015-03-23 10:49:30 +03:00

18 lines
No EOL
1.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

Нужно найти начало комментария <code class="match">&lt;!--</code>, затем всё до конца <code class="match">--&gt;</code>.
С первого взгляда кажется, что это сделает регулярное выражение <code class="pattern">&lt;!--.*?--&gt;</code> -- квантификатор сделан ленивым, чтобы остановился, достигнув <code class="match">--&gt;</code>.
Однако, точка в JavaScript -- любой символ, *кроме* конца строки. Поэтому такой регэксп не найдёт многострочный комментарий.
Всё получится, если вместо точки использовать полностю "всеядный" <code class="pattern">[\s\S]</code>.
Итого:
```js
//+ run
var re = /<!--[\s\S]*?-->/g;
var str = '.. <!-- Мой -- комментарий \n тест --> .. <!----> .. ';
alert( str.match(re) ); // '<!-- Мой -- комментарий \n тест -->', '<!---->'
```