如果你看一下_.template
implementation,你會看到你的問題的根源:
_.template = function(text, data, settings) {
//...
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
//...
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
所以_.template
預計這三個模板分隔符表達式來只包含一個捕獲組; noMatch
佔位符只是/(.)^/
,因此它不會匹配任何內容,但仍包含必需的捕獲組。您試圖包含兩個拍攝組所示:
/(?:\{\{(.+?)\}\})|(?:\<\%\=(.+?)\%\>)/g
// ^^^ ^^^
第二<%=...%>
組是你的煩惱背後。
你或許可以逃脫這樣的:
/(?:\{\{|<%=)(.+?)(?:%>|\}\})/g
但是,這會看到這樣<%= pancakes}}
和{{pancakes %>
爲模板表達的東西。儘管如此,我認爲你不必擔心這樣的事情。
這就是說,你應該能夠自動將您的模板和一些非常簡單的正則表達式的工作更新到你喜歡的樣式,只是通過自己喜歡的工具的版本中發送所有模板:
s/\{\{(.+?)\}\}/<%= $1 %>/g
在JavaScript中你」 d有:
// read your template into old_school
new_school = old_school.replace(/\{\{(.+?)\}\}/g, '<%= $1 %>');
// replace your template with the content of new_school
然後,你不必擔心上面的時髦的正則表達式或有兩組分隔符。