表达式中涉及数学除法时,如何使用vim regex替换文本 [英] How can I use vim regex to replace text when math divide is involved in the expression
问题描述
我正在使用vim处理如下文本
I am using vim to process text like the following
0x8000 INDEX1 ....
0x8080 INDEX2 ....
....
0x8800 INDEXn ....
我想使用正则表达式获取每行的索引号.那是
I want to use regular expression to get the index number of each line. that is
0x8000 ~ 0
0x8080 ~ 1
....
0x8800 ~ n
数学评估应为(hex-0x8000)/0x80.我正在尝试使用vim正则表达式替换来获取结果
The math evaluation should be (hex - 0x8000) / 0x80. I am trying to using vim regular expression substitution to get the result in line
%s/^\(\x\+\)/\=printf("%d", submatch(1) - 0x8000)
这将产生
0 INDEX0
128 INDEX1
....
2048 INDEXn
我想要做的是将其进一步更改为
What I want to do is to further change it to
0 INDEX0
1 INDEX1
...
20 INDEXn
也就是说,我想用0x80进一步划分第一列.这是我遇到问题的时候.
That is, I want to further divide the first column with an 0x80. Here is when I get the problem.
原始参数为"submatch(1)-0x8000".我现在在其中添加一个"/0x80",它形成
The original argument is "submatch(1) - 0x8000". I now add an "/ 0x80" to it, which forms
%s/^\(\x\+\)/\=printf("%d", (submatch(1) - 0x8000)\/0x80)
现在Vim报告错误
Invalid expression: printf("%d", (submatch(1) - 0x8000)\/0x80))
处理"/"时似乎vim遇到问题.我也尝试使用单个"/"(不进行转义),但仍然失败.
It looks like vim meet problem when processing "/". I also tried with a single "/" (without escape), but still fails.
有人可以帮我吗?
推荐答案
您不能在sub-replace-expression
中使用分隔字符.
从
:h sub-replace-expression
:
You can't use the separation character in a sub-replace-expression
.
From
: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
:
Note that I had to change your regex (specifically ^\(\x\+\)
to ^\(0x\x\+\)
). I don't know why yours works for you, but from :h character-classes
, \x
shouldn't include the trailing 0x
:
/\x \x \x hex digit: [0-9A-Fa-f]
此外,使用非常魔术的模式(请参见:h magic
),您的正则表达式(至少对我来说)更容易阅读:
Also, your regex is a bit easier to read (to me at least) using very-magic mode (see :h magic
):
:%s#\v^(0x\x+)#\=printf("%d", (submatch(1) - 0x8000)/0x80)
这篇关于表达式中涉及数学除法时,如何使用vim regex替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!