Reputation: 32721
I'd like to create a shortcut to convert rem to px and px to rem for CSS file in vimrc.
""""for converting px to rem""""
nnoremap <Leader>rem :%s; \(\d*\)px;\= string(submatch(1) / 16.0) . "rem";
""""for converting rem to px"""
nnoremap <Leader>px :%s; \(\d*\)rem;\= string(submatch(1) * 16.0) . "px";
The first one works but not the second one. When rem has a decimal, it doesn't convert to px.
How can I improve this code?
======= After the help of KoRoN the following is my final solution
""""for converting px to rem""""
nnoremap <Leader>rem :%s;\<\(\d*\)px;\= float2nr(submatch(1) / 16.0) . "rem";
""""for converting rem to px"""
nnoremap <Leader>px :%s;\<\(\d\+\%(\.\d\+\)\?\)rem;\= float2nr(str2float(submatch(1)) * 16.0) . "px";
Upvotes: 0
Views: 172
Reputation: 375
Try to use \(\d\+\%(\.\d\+\)\?\)
instead of \(\d*\)
for decimal (float).
This pattern is not perfect, but will cover most of cases.
And you should convert string to float by using str2float
.
As a result of these, your second map should be like this:
nnoremap <Leader>px :%s; \(\d\+\%(\.\d\+\)\?\)rem;\= string(str2float(submatch(1)) * 16.0) . "px";
Upvotes: 2