0

到目前为止,我在尝试在 javascript 匹配中使用多个反向引用时遇到了麻烦:-

function newIlluminate() {
  var string = "the time is a quarter to two";
  var param = "time";

   var re = new RegExp("(" + param + ")", "i");

    var test = new RegExp("(time)(quarter)(the)", "i");

  var matches = string.match(test);

  $("#debug").text(matches[1]);

}

newIlluminate();

#Debug匹配正则表达式're'时打印'time',它是param的值。

我已经看到了匹配示例,其中通过将匹配包含在括号中来使用多个反向引用,但是我的匹配(时间)(季度)...返回 null。

我哪里错了?任何帮助将不胜感激!

4

2 回答 2

1

您的正则表达式实际上是在寻找timequarterthe匹配项(如果找到一个)并将其拆分为三个反向引用。

我想你的意思是:

var test = /time|quarter|the/ig;
于 2013-08-17T13:26:29.590 回答
1

您的正则表达式test根本不匹配string(因为它不包含 substring timequarterthe)。我猜你想要交替

var test = /time|quarter|the/ig; // does not even need a capturing group
var matches = string.match(test);

$("#debug").text(matches!=null ? matches.join(", ") : "did not match");
于 2013-08-17T13:27:25.860 回答