我大致有以下源数据,我试图通过vim的regexp搜索和替换来执行全局替换:
"text": [{
"uid": "...",
"left": 50,
"top": 715,
"minSize": 60,
"maxSize": 70,
"width": "345px",
"align": "center",
"font": "...",
"forbidden": "",
"border": true,
"printType": 0
}
Run Code Online (Sandbox Code Playgroud)
我的搜索/替换字符串如下所示:
:%s/"left": \(\d\+\)/"left": \=submatch(1)*0.66/g
实际上,我试图"left"在所有情况下将财产减少到其当前价值的66%.
不幸的是,结果字符串变为:
"text": [{
"uid": "...",
"left": =submatch(1)*0.66,
"top": 715,
"minSize": 60,
"maxSize": 70,
"width": "345px",
"align": "center",
"font": "...",
"forbidden": "",
"border": true,
"printType"
Run Code Online (Sandbox Code Playgroud)
所以,而不是让"left": 33我得到"left": =submatch(1)*0.66.
起初,我认为这是因为我正在使用=submatch(0).但是,切换到=submatch(0)没有修复问题,只是=submatch(0)在替换后的字符串中返回.
是否会出现无法正确评估表达式的情况?
在替换中使用表达式时,替换必须以\=,然后将其余部分计算为表达式.在你的情况下,你刚刚逃过等号.
最简单的方法是使用\zs在数字之前开始匹配
:%s/"left": \zs\d\+/\=submatch(0) * 0.66
Run Code Online (Sandbox Code Playgroud)
然后submatch(0)用于整场比赛,在这种情况下只是数字.