还是正则表达式的替代会返回比预期更多的结果?

时间:2019-04-25 08:21:01

标签: javascript regex

该代码是从https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_regexp_xy修改而来的。

<p>Click the button to do a global search for any of the specified alternatives (red|green).</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
  function myFunction() {
    var str = "re, green, red, green, gren, gr, blue, yellow";
    var patt1 = /(blue|red)/;
    var result = str.match(patt1);
    document.getElementById("demo").innerHTML = result;
  }
</script>

结果为red,red。但是,只有一个red。为什么返回两个?

2 个答案:

答案 0 :(得分:2)

您不应使用在替代方案上有效的捕获组。从正则表达式中删除()

更改

var patt1 = /(blue|red)/;

收件人

var patt1 = /blue|red/;

<p>Click the button to do a global search for any of the specified alternatives (red|green).</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
  function myFunction() {
    var str = "re, green, red, green, gren, gr, blue, yellow";
    var patt1 = /blue|red/;
    var result = str.match(patt1);
    document.getElementById("demo").innerHTML = result;
  }
</script>

答案 1 :(得分:2)

因为在正则表达式中使用组,所以match会重新匹配匹配的字符串和组(因此数组中两个元素相同)。改用/blue|red/gg使match在findig首次匹配后将继续搜索)

function myFunction() {
  var str = "re, green, red, green, gren, gr, blue, yellow";
  var patt1 = /blue|red/g;
  var result = str.match(patt1);
  demo.innerHTML = result;
}
<p>Click the button to do a global search for any of the specified alternatives (red|green).</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>