简体   繁体   English

仅在不匹配的情况下使用RegEx替换括号内的值

[英]Replace value inside brackets using RegEx only where does not match

How can I replace the number inside the brackets for any strings not matching the word "Field". 如何将括号内的数字替换为与“字段”一词不匹配的任何字符串。 So the number inside 'SomethingElse' and 'SomethingMore' could be replaced to a new value, but any bracketed value to the right side of the term 'Field' would not be touched. 因此,'SomethingElse'和'SomethingMore'中的数字可以替换为新值,但是不会触及术语'Field'右侧的任何括号内的值。 Note, the word "Field" will always stay the same, so it can be referenced as a magic string in the regex. 请注意,单词“Field”将始终保持不变,因此可以在正则表达式中将其引用为魔术字符串。

Field[50].SomethingElse[30]
Field[50].SomethingMore[30]

Thanks. 谢谢。 PS. PS。 Using JavaScript. 使用JavaScript。

str.replace(/\b((?!Field\[)\w+)\[\d+\]/g, '$1[' + repl + ']');

尝试

str.replace(/(Field\[[^\]]*\]\.[^\[]*)\[(.*)\]/g, "$1["+value+"]");

str.replace(/(?<!Field)\\[([\\d]*)\\]]/g, '$1['+newnumber+']');

希望这可以帮助

You could use "eval" and string manipulation, but if you have to do it that way, you're doing it wrong. 你可以使用“eval”和字符串操作,但是如果你必须这样做,那你就错了。

Storing the number "30" to a variable allows it to be manipulated as you require, then just access "SomethingElse" and "SomethingMore" as follows: 将数字“30”存储到变量允许根据需要进行操作,然后只需访问“SomethingElse”和“SomethingMore”,如下所示:

var n = 30;
// conditional logic;

Field[50].SomethingElse[n]
Field[50].SomethingMore[n]

Regards, Joshua 此致,约书亚

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM