我需要解析HTML文件并提取以下标志中的任何字符:
${
{消息{1}}
消息可能包含单词,空格甚至特殊字符。我有以下似乎部分工作的正则表达式:
}
这种模式发生的事情似乎是从换行符向后工作并找到第一个/\$\{(.+)\}/g
。期望的结果是向前工作并找到第一个}
。
以下是RegExr中的正则表达式:https://regexr.com/3ng3d
我有以下测试用例:
}
正则表达式应该提取以下内容:
但我实际得到的是......
看起来我的正则表达式正在从\ n开始工作并找到第一个<div>
<div class="panel-heading">
<h2 class="panel-title">${Current Status}<span> - {{data.serviceDisplay}}</span></h2>
</div>
${test}
<div class="panel-body">
<div>${We constantly monitor our services and their related components.} ${If there is ever a service interruption, a notification will be posted to this page.} ${If you are experiencing problems not listed on this page, you can submit a request for service.}</div>
<div>
<div>${No system is reporting an issue}</div>
</div>
<div>
<a>{{outage.typeDisplay}} - {{outage.ci}} (${started {{outage.begin}}})
<div></div>
</a>
</div>
<div><a href="?id=services_status" aria-label="${More information, open current status page}">${More information...}
</a></div>
</div>
</div>
,它正在给我#1,#3和#6。
我如何从头开始工作并找到第一个}
而不是从换行符向后工作?
答案 0 :(得分:2)
使用RegExp.exec()
迭代文本并提取捕获组。
模式是/\$\{(.+?)\}(?=[^}]+?(?:{|$))/g
- 延迟匹配字符,直到关闭大括号,后面是以开头大括号或字符串结尾结束的序列。
var pattern = /\$\{(.+?)\}(?=[^}]+?(?:{|$))/g;
var text = '<div>\
<div class="panel-heading">\
<h1>${Text {{variable}} more text}</h1>\
<h2 class="panel-title">${Current Status}<span> - {{data.serviceDisplay}}</span></h2>\
</div>\
${test}\
<div class="panel-body">\
<div>${We constantly monitor our services and their related components.} ${If there is ever a service interruption, a notification will be posted to this page.} ${If you are experiencing problems not listed on this page, you can submit a request for service.}</div>\
<div>\
<div>${No system is reporting an issue}</div>\
</div>\
<div>\
<a>{{outage.typeDisplay}} - {{outage.ci}} (${started {{outage.begin}}})\
<div></div>\
</a>\
</div>\
<div><a href="?id=services_status" aria-label="${More information, open current status page}">${More information...}\
</a></div>\
</div>\
</div>';
var result = [];
var temp;
while(temp = pattern.exec(text)) {
result.push(temp[1]);
}
console.log(result);
&#13;