简体   繁体   中英

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. Note, the word "Field" will always stay the same, so it can be referenced as a magic string in the regex.

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

Thanks. PS. Using 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.

Storing the number "30" to a variable allows it to be manipulated as you require, then just access "SomethingElse" and "SomethingMore" as follows:

var n = 30;
// conditional logic;

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

Regards, Joshua

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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