使用正则表达式,我希望能够获得每个匹配项并将其替换为特定的内容

Using regex, I want to be able to get each match and replace it with something specific

如果我有以下字符串:

The dog, the cat and the Catterpillar.

和匹配 'cat'(大写或小写)的正则表达式,在 'cat' 和 'cat[ 中会有两个匹配项=19=]毛毛虫'。到目前为止一切顺利,但如果比赛有 space 或之后没有,我想替换条件下的那些。例如,第一个 'cat' 将替换为 X,而 'catterpillar' 中的 'cat' 将替换为 Y。

有没有办法使用 jQuery 来完成这个?有条件地替换匹配项?

var str = "The dog, the cat and the Catterpillar."
str.replace(/cat /gi, "X ");
str.replace(/cat/gi, "Y");

是的,你可以使用边界:

/\bcat\b/i
'The dog, the cat and the Catterpillar.'.replace(/\bcat\b/i, 'horse')

或者,如果您真的只想将 space 作为定界符,则可以使用正向先行:

/cat(?= )/i
'The dog, the cat and the Catterpillar.'.replace(/cat(?= )/i, 'horse')

str.replace( regexp|substr, newSubStr|function [, flags])

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

我们可以使用可选的 group:

/cat( )?/gi

并使用一个函数来评估组是否已设置:

var str = "The dog, the cat and the Catterpillar."

var result = str.replace(/cat( )?/gi, function (match,space) {
    if (typeof space === "undefined") {
        return 'Y';
    } else {
        return 'X' + space;
    }
});

document.body.innerText += result;