当表达式中涉及数学除法时,如何使用 vim 正则表达式替换文本

How can I use vim regex to replace text when math divide is involved in the expression

我正在使用 vim 来处理如下文本

0x8000   INDEX1 ....
0x8080   INDEX2 ....
....
0x8800   INDEXn ....

我想用正则表达式来获取每一行的索引号。即

0x8000 ~ 0
0x8080 ~ 1
....
0x8800 ~ n

数学计算应该是 (hex - 0x8000) / 0x80。我正在尝试使用 vim 正则表达式替换来获得行

中的结果
%s/^\(\x\+\)/\=printf("%d", submatch(1) - 0x8000)

这将产生

0     INDEX0
128   INDEX1
....
2048  INDEXn

我想做的是进一步改成

0     INDEX0
1     INDEX1
...
20    INDEXn

也就是我想把第一列进一步分割成一个0x80。这是我遇到问题的时间。

原参数为"submatch(1) - 0x8000"。我现在给它添加一个“/ 0x80”,形成

%s/^\(\x\+\)/\=printf("%d", (submatch(1) - 0x8000)\/0x80)

现在Vim报错

Invalid expression: printf("%d", (submatch(1) - 0x8000)\/0x80))

看起来 vim 在处理“/”时遇到问题。我也尝试过使用单个“/”(没有转义),但仍然失败。

谁能帮我解决这个问题?

您不能在 sub-replace-expression 中使用分隔符。
:h sub-replace-expression :

Be careful: The separation character must not appear in the expression!
Consider using a character like "@" or ":".  There is no problem if the result
of the expression contains the separation character.

改为更改分隔符以不再匹配除法运算符。例如,使用 #.

:%s#^\(0x\x\+\)#\=printf("%d", (submatch(1) - 0x8000)/0x80)

请注意,我必须更改您的正则表达式(特别是 ^\(\x\+\)^\(0x\x\+\))。我不知道你的为什么对你有用,但是从 :h character-classes\x 不应该包括尾随的 0x :

/\x     \x      \x      hex digit:                      [0-9A-Fa-f] 

此外,使用非常神奇的模式(请参阅 :h magic),您的正则表达式更容易阅读(至少对我而言):

:%s#\v^(0x\x+)#\=printf("%d", (submatch(1) - 0x8000)/0x80)