从字符串中提取字符

时间:2018-04-06 17:48:24

标签: javascript regex

我需要解析HTML文件并提取以下标志中的任何字符:

${ {消息{1}}

消息可能包含单词,空格甚至特殊字符。我有以下似乎部分工作的正则表达式:

}

这种模式发生的事情似乎是从换行符向后工作并找到第一个/\$\{(.+)\}/g 。期望的结果是向前工作并找到第一个}

以下是RegExr中的正则表达式:https://regexr.com/3ng3d

我有以下测试用例:

}

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

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

    1. $ {当前状态} - {{data.serviceDisplay}}
    2. $ {测试}
    3. $ {我们会不断监控我们的服务及其相关组件。} $ {如果4.服务中断,则会在此页面上发布通知。} $ {如果您遇到此页未列出的问题,您可以提交服务请求。}
    4. $ {没有系统报告问题}
    5. $ {已启动{{outage.begin}}}
    6. $ {更多信息,请打开当前状态页}}> $ {更多信息...}
    7. 看起来我的正则表达式正在从\ 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。

      我如何从头开始工作并找到第一个}而不是从换行符向后工作?

1 个答案:

答案 0 :(得分:2)

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

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

RegExr demo

&#13;
&#13;
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;
&#13;
&#13;

相关问题