【问题标题】:is there any way to get results of grouping along with all the matched regex strings有什么方法可以得到分组结果以及所有匹配的正则表达式字符串
【发布时间】:2014-12-01 06:46:53
【问题描述】:

我想获得正则表达式匹配的结果以及组匹配

输入字符串:

  var str= ' application [<!ENTITY % common  SYSTEM "../common.ent">\n%common;] <!ENTITY % name PUBLIC "public_ID" "URI">'

正则表达式:

   var rg = /<!ENTITY\s+[\%|\&]?\s*(\S+)\s+(PUBLIC|SYSTEM)\s+"([^"]*)"\s*(?:"([^"]*)"\s*)?>/g

申请

str.match(rg)

只产生匹配的字符串:

["<!ENTITY % common  SYSTEM "../common.ent">", "<!ENTITY % name PUBLIC "public_ID" "URI">"]

如何获取组匹配结果?

例如,在这种情况下,我期待这样的事情:

[{
   matched : "<!ENTITY % common  SYSTEM "../common.ent">",
   groups : ["common", "SYSTEM", "../common.ent"]
}, {
   matched : "<!ENTITY % name PUBLIC "public_ID" "URI">",
   groups : ["name", "PUBLIC", "public_ID", "URI"]
}]

编辑: 只是有点想知道 regex101.com 如何 显示此

参考:http://regex101.com/r/oU0qN5/1

【问题讨论】:

  • 我的回答有帮助吗,还是我遗漏了什么?

标签: javascript regex


【解决方案1】:

在javascript中一次调用是不可能的,你必须循环调用它

var str= ' application [<!ENTITY % common  SYSTEM "../common.ent">\n%common;] <!ENTITY % name PUBLIC "public_ID" "URI">';
var rg = /<!ENTITY\s+[\%|\&]?\s*(\S+)\s+(PUBLIC|SYSTEM)\s+"([^"]*)"\s*(?:"([^"]*)"\s*)?>/g;

var result;
var results = [];
while(result = rg.exec(str)){
  results.push(result);
}

// this part and they join is just to display the result
document.getElementById("result").innerText = results.join("@@@@");
document.getElementById("result").innerHTML =     document.getElementById("result").innerHTML.replace("@@@@","<br/>");

// tested with Win7 Chrome 38+
&lt;div id="result"&gt;&lt;/div&gt;

不是你想要的结构,但是像这样可以用 Javascript 完成

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-17
    • 2019-09-18
    • 2016-03-26
    • 2020-05-06
    • 2015-08-01
    • 2013-02-17
    • 2017-03-17
    • 1970-01-01
    相关资源
    最近更新 更多