我需要解析 HTML 文件并提取在以下标志中找到的任何字符:
${
消息}
消息可能包含单词、空格,甚至特殊字符。我有以下正则表达式,似乎部分有效:
/\$\{(.+)\}/g
此模式发生的情况是,它似乎从换行符开始向后工作并找到第一个 }
。期望的结果是继续前进并找到第一个 }
。
这是 RegExr 中的正则表达式:https://regexr.com/3ng3d
我有以下测试用例:
<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>
正则表达式应提取以下内容:
- 当前状态
- 测试
- 我们不断监控我们的服务及其相关组件。
- 如果出现服务中断,我们会在此页面发布通知。
- 如果您遇到本页未列出的问题,您可以提交服务请求。
- 没有系统报告问题
- 开始{{outage.begin}}
- 了解更多信息,请打开当前状态页面
- 更多信息...
但我实际上得到的是......
- ${当前状态} - {{data.serviceDisplay}}
- ${测试}
- ${我们不断监控我们的服务及其相关组件。} ${如果 4. 出现服务中断,我们将在此页面发布通知。} ${如果您遇到此页面未列出的问题,您可以提交服务请求。}
- ${没有系统报告问题}
- ${开始{{outage.begin}}}
- ${更多信息,打开当前状态页面}">${更多信息...}
看来我的正则表达式正在从\n 开始工作,并找到第一个 }
,这就是给我 #1、#3 和 #6 的原因。
如何从头开始工作并找到第一个 }
而不是从换行符开始向后工作?
最佳答案
使用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);
关于javascript - 从字符串中提取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49698453/