我正在研究一个字符串,它是这样的(这是一个很长的字符串,有500+个值,它将以递增的方式运行,如这个例子所示。) )
Select "start_date", "pmcounter"[1] as "pmcounter[1]", "pmcounter"[2] as "pmcounter[2]" ,"pmcounter"[31] as "pmcounter[31]" from view
我想让这个字符串看起来像
Select "start_date", "pmcounter"[1] as "pmcounter_1", "pmcounter"[2] as "pmcounter_2" ,"pmcounter"[31] as "pmcounter_31" from view
为此,我做了这段代码。(我是一个非常初级的水平,你可以从我的代码中看出:) )
var fields = "Select \"start_date\", \"pmcounter\"[1] as \"pmcounter[1]\", \"pmcounter\"[2] as \"pmcounter[2]\" ,\"pmcounter\"[31] as \"pmcounter[31]\" from view";
fields = fields.replace(/\[1\]\"/,'_1\"')
fields = fields.replace(/\[2\]\"/,'_2\"')
fields = fields.replace(/\[3\]\"/,'_3\"')
fields = fields.replace(/\[31\]\"/,'_31\"')
// const regex = new RegExp("ReGeX"+n+"ReGeX");
console.log(fields);
输出。
Select "start_date", "pmcounter"[1] as "pmcounter_1", "pmcounter"[2] as "pmcounter_2" ,"pmcounter"[31] as "pmcounter_31" from view
你能告诉我一个简单的方法吗?一些For循环。
你可以使用捕捉到的组,并在替换时使用回溯引用
\[(\d+)\]"
^^^^^
--------- Capture group, which we are referencing by `$1` in replace callback
const fields = "Select \"start_date\", \"pmcounter\"[1] as \"pmcounter[1]\", \"pmcounter\"[2] as \"pmcounter[2]\" ,\"pmcounter\"[31] as \"pmcounter[31]\" from view";
console.log(fields.replace(/\[(\d+)\]"/g, '_[' + "$1" + ']"'))