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

时间:2016-01-25 12:10:38

标签: javascript jquery regex substr

我有一个这样的字符串:

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

此字符串中的捕获组$1 returns 2

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

2 个答案:

答案 0 :(得分:3)

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

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)";




答案 1 :(得分:0)

也许这样的构建可以提供帮助(来源: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);
}