使用 RegExp 获取字符串的最后一次出现位置

问题描述 投票:0回答:5

假设我的文字如下:

购买这款手机的一个令人信服的原因可能是它的显示屏。当然,我们会喜欢全高清,但我们再次因为高昂的价格而闭嘴。屏幕响应能力也不错。

我只想获取文本中最后一次出现“the”字符串的索引。(使用正则表达式)

var re = new RegExp("\\b"+"the"+"\\b",'g');
var pos = re.lastIndex;

仅给出字符串第一次出现的位置

the
..
有什么建议么?

javascript regex
5个回答
4
投票

为什么需要正则表达式来查找子字符串的最后一次出现。您可以使用本机

.lastIndexOf()
方法:

re.lastIndexOf("the");

1
投票

单向;

var pos = -1;
while ((match = re.exec(str)) != null)
    pos = match.index;

alert("last match found at " + pos);

0
投票

正则表达式是

/\bthe\b(?!(.|\n)*\bthe\b)/
(无全局标志!)...意思是单词“the”后面没有单词“the”。

测试:

var re = new RegExp('\\b' + input + '\\b(?!(.|\\n)*\\b' + input + '\\b)');
var pos = re.test(str) ? re.exec(str).index : -1;

0
投票

这是一个可行的解决方案,即使使用非全局正则表达式:

    function regexLastIndexOf(str, regex) {
        regex = regex.global
            ? regex
            : new RegExp(regex.source, 'g' + (regex.ignoreCase ? 'i' : '') + (regex.multiLine ? 'm' : ''));
        var lastIndexOf = -1;   
        var nextStop = 0;
        var result;
        while ((result = regex.exec(str)) != null) {
            lastIndexOf = result.index;
            regex.lastIndex = ++nextStop;
        }
        return lastIndexOf;
    }

0
投票

const lastIndexOfRegex = (str, regex) => {
  const match = str.match(regex)
  return match ? str.lastIndexOf(match[match.length - 1]) : -1
}

const result = lastIndexOfRegex('test po2 po44', /[a-z][a-z][0-9]/)

console.log(result)

© www.soinside.com 2019 - 2024. All rights reserved.