进行此正则表达式替换的好方法

Nice way to do this regex substitution

本文关键字:方法 替换 正则表达式      更新时间:2023-09-26

我正在编写一个javascript函数,它需要一个正则表达式和一些元素,它将正则表达式与name属性进行匹配。

假设我通过了这个正则表达式

/cmw_step_attributes']'['d*']/

以及结构如下的字符串

"foo[bar][]chicken[123][cmw_step_attributes][456][name]"

所有数字都可能变化或丢失。 我想将正则表达式与字符串匹配,以便将 456 换成另一个数字(会有所不同),例如 789。 所以,我想结束

"foo[bar][]chicken[123][cmw_step_attributes][789][name]"
正则表达式

将与字符串匹配,但我无法将整个正则表达式换成 789,因为这会清除"[cmw_step_attributes]["位。 必须有一种干净简单的方法来做到这一点,但我无法理解它。 有什么想法吗?

谢谢,马克斯

捕获第一部分并将其放回字符串中。

.replace(/(cmw_step_attributes']'[)'d*/, '$1789');
// note I removed the closing ] from the end - quantifiers are greedy so all numbers are selected
// alternatively:
.replace(/cmw_step_attributes']'['d*']/, 'cmw_step_attributes][789]')

要么从字面上重写替换字符串中必须保持不变的部分,要么将其放在捕获括号内并替换引用它。

请参阅答案:正则表达式以匹配外括号。

正则表达式是错误的工具,因为您正在处理嵌套结构,即递归。

你试过吗:

var str = 'foo[bar][]chicken[123][cmw_step_attributes][456][name]';
str.replace(/cmw_step_attributes']'['d*?']/gi, 'cmw_step_attributes][XXX]');