Javascript 做这个正则表达式替换的好方法
我正在编写一个javascript函数,它接受一个正则表达式和一些元素,它将正则表达式与name属性相匹配 假设我通过了这个正则表达式Javascript 做这个正则表达式替换的好方法,javascript,regex,Javascript,Regex,我正在编写一个javascript函数,它接受一个正则表达式和一些元素,它将正则表达式与name属性相匹配 假设我通过了这个正则表达式 /cmw_step_attributes\]\[\d*\]/ 还有一个这样构造的字符串 "foo[bar][]chicken[123][cmw_step_attributes][456][name]" 所有的数字可能会有所不同,或是丢失。我想将正则表达式与字符串匹配,以便将456换成另一个数字(会有所不同),例如789。所以,我想以 "foo[bar][]c
/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][”位。必须有一种干净简单的方法来实现这一点,但我无法理解它。有什么想法吗
谢谢,max捕获第一部分并将其放回字符串中
.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]')
捕获第一部分并将其放回字符串中
.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]');
您是否尝试过:
var str = 'foo[bar][]chicken[123][cmw_step_attributes][456][name]';
str.replace(/cmw_step_attributes\]\[\d*?\]/gi, 'cmw_step_attributes][XXX]');
谢谢@Kolink。那里的
$1
是怎么回事?这里的$1
是对捕获的子模式的引用,在这里是cmw\u步骤属性\][
。谢谢@Kolink。$1
是对捕获的子模式的引用,在这里是cmw\u步骤属性\]\[
。那会起作用,但我如何动态地做呢,即如果我可以通过任何正则表达式来匹配字符串,并且想要切换出\d部分?@MaxWilliams,就像任何替换cmw\u step\u attributes的东西一样?
?那会起作用,但我如何动态地做呢,即如果我可以通过任何正则表达式来匹配字符串字符串,是否要切换出\d部分?@MaxWilliams是否要替换cmw\u step\u属性
?