Regex在JavaScript中,我可以只替换内部特定组而不是完整字符串吗?


regex: Morning, ((.*?) (.*?) (.*?) group)
input: Morning, I am inner group

请参阅以上代码。在本例中,我想替换"inner"嵌套",但我找不到这样做的方法。我所见过的所有替换方法都是用于平面分组(不嵌套)或替换整行。

我可以知道是否有办法达到我想要的吗?提前谢谢。

这是可能的,但是您需要为hasIndices指定d标志,以便您可以获得特定组的索引。

一旦你得到了该组的开始和结束索引,你就可以很容易地将第一部分和第二部分连接起来:

const regex = /Morning, ((.*?) (.*?) (.*?) group)/d;
const input = "Morning, I am inner group";
// in this case, you want to get the indices of the 4th group
const [start, end] = input.match(regex).indices[4];
const output = input.slice(0, start) + 'nested' + input.slice(end);
console.log(output);

最新更新