有没有办法得到分组的结果以及所有匹配的正则表达式字符串

时间:2014-12-01 06:46:54

标签: javascript regex

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

输入字符串:

  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 显示此enter image description here

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

1 个答案:

答案 0 :(得分:0)

在一次通话的javascript中无法进行,你必须在循环中调用它

&#13;
&#13;
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+
&#13;
<div id="result"></div>
&#13;
&#13;
&#13;

不在您想要的结构中,但是像这样可以在Javascript中完成