gpt4 book ai didi

javascript - 从字符串中提取字符

转载 作者:行者123 更新时间:2023-11-29 20:55:08 29 4
gpt4 key购买 nike

我需要解析 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>

正则表达式应提取以下内容:

  1. 现状
  2. 测试
  3. 我们会持续监控我们的服务及其相关组件。
  4. 如果服务中断,将向此页面发布通知。
  5. 如果您遇到此页面上未列出的问题,您可以提交服务请求。
  6. 没有系统报告问题
  7. 开始{{outage.begin}}
  8. 更多信息,打开当前状态页面
  9. 更多信息...

但我实际得到的是...

  1. ${当前状态} - {{data.serviceDisplay}}
  2. ${测试}
  3. ${我们不断监控我们的服务及其相关组件。} ${如果 4. 服务中断,将向此页面发布通知。} ${如果您遇到此页面未列出的问题,您可以提交服务请求。
  4. ${没有系统报告问题}
  5. ${开始{{outage.begin}}}
  6. ${更多信息,打开当前状态页面}">${更多信息...}

看来我的正则表达式正在从\n 返回并找到第一个 ,这是给我 #1、#3 和 #6 的原因。

我怎样才能从头开始工作并找到第一个 而不是从换行符开始倒退?

最佳答案

使用RegExp.exec() 迭代文本并提取捕获组。

模式是 /\$\{(.+?)\}(?=[^}]+?(?:{|$))/g - 字符延迟匹配直到右大括号后跟以左大括号或字符串结尾结尾的序列。

RegExr demo

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com