如何仅对字符串的一部分应用正则表达式?

How to apply a regex just for a part of string?

我有这样的字符串:

var str = "this is test
            1. this is test
            2. this is test
            3. this is test
            this is test
             1. this test   
             2. this is test
            this is test";

我也有这个正则表达式:

/^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m

这个捕获组 </code> returns <code>2 来自上面的字符串。

现在我有一个位置编号:65,我想在字符串的这个范围内应用该正则表达式:[0 - 65]。 (所以我必须得到 3 而不是 2)。一般来说,我想将该字符串从第一个限制到一个特定的位置,然后在该范围内应用该正则表达式。我该怎么做?

也许这样的构建可以提供帮助(来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

var myRe = /ab*/g;
var str = 'abbcdefabh';
var myArray;
while ((myArray = myRe.exec(str)) !== null) {
  var msg = 'Found ' + myArray[0] + '. ';
  msg += 'Next match starts at ' + myRe.lastIndex;
  console.log(msg);
}

最简单的方法是仅将其应用于该子字符串:

var match = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(str.substring(0, 65));
// Note ----------------------------------------------------------------^^^^^^^^^^^^^^^^^

示例:

var str = "this is test\n1. this is test\n2. this is test\n3. this is test\nthis is test\n1. this test   \n2. this is test\nthis is test";
var match = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(str.substring(0, 65));
    // Note ----------------------------------------------------------------^^^^^^^^^^^^^^^^^

document.body.innerHTML = match ? "First capture: [" + match[1] + "]" : "(no match)";