是否有一种方法来检索(开始)字符的位置在一个正则匹配()在Javascript的结果字符串?


当前回答

Exec返回一个带有index属性的对象:

Var match = /bar/.exec("foobar"); If (match) { Console.log ("match found at " + match.index); }

对于多个匹配:

Var re = /bar/g, STR = "foobarfoobar"; While ((match = re.exec(str)) != null) { Console.log ("match found at " + match.index); }

其他回答

这是我想到的:

//查找引用文本的开始和结束位置 //双引号或单引号,支持转义字符,如\" \' Var STR = "这是一个带引号的字符串,因为你可以'读'"; var型 = /'((?:\\.|[^'])*)'|"((?:\\.|[^"])*)"/ igm; While (match = pat .exec(str)) { console.log(匹配。index + ' ' + pat . lastindex); }

来自developer.mozilla.org文档的String .match()方法:

返回的数组有一个额外的输入属性,该属性包含 被解析的原始字符串。此外,它还有一个索引 属性中匹配的从零开始的索引 字符串。

当处理一个非全局的正则表达式(即,在你的正则表达式上没有g标志)时,.match()返回的值有一个index属性…你要做的就是进入它。

var index = str.match(/regex/).index;

下面是一个例子,展示了它的工作原理:

Var STR = '我的字符串这里'; Var index = str.match(/here/).index; console.log(指数);// <- 10

我已经成功地测试了IE5。

在现代浏览器中,您可以使用string.matchAll()来实现这一点。

与RegExp.exec()相比,这种方法的优点是它不依赖于正则表达式是有状态的,就像@Gumbo的答案中那样。

让regexp = /bar/g; 让STR = 'foobarfoobar'; let matches =[…str.matchAll(regexp)]; matches.forEach((match) => { Console.log ("match found at " + match.index); });

var str = "The rain in SPAIN stays mainly in the plain";

function searchIndex(str, searchValue, isCaseSensitive) {
  var modifiers = isCaseSensitive ? 'gi' : 'g';
  var regExpValue = new RegExp(searchValue, modifiers);
  var matches = [];
  var startIndex = 0;
  var arr = str.match(regExpValue);

  [].forEach.call(arr, function(element) {
    startIndex = str.indexOf(element, startIndex);
    matches.push(startIndex++);
  });

  return matches;
}

console.log(searchIndex(str, 'ain', true));

var str = '我的字符串在这里'; var index = str.match(/hre/).index; 警报(索引),<- 10