Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert C style cast to C++ style cast in vim

Tags:

c++

vim

I got hand over some legacy code and first I want to change

(int)a + b;

into

static_cast<int>(a) + b;

There are a lot of them and doing them manually is very time consuming. Is there a way to use vim to make this happen?

I tried something like

:%s/\(int\).* /static_cast<int>(\2)/g

but it doesn't work. Please advice.

like image 667
user3667089 Avatar asked Jan 15 '16 03:01

user3667089


1 Answers

Try this:

:%s/(\(.*\))\([^ ]*\)/static_cast<\1>(\2)/g

This regex, as per your question, assumes that there will be a space after the variable name:

Example:
For following test data:

(int)a + b
(float)x * y
(int)z+m

result will be

static_cast<int>(a) + b
static_cast<float>(x) * y
static_cast<int>(z+m)

Explaining the regex

(\(.*\)) - Match whatever is inside () and capture it
\([^ ]*\) - followed by anything which is not a space and capture it

like image 197
xk0der Avatar answered Oct 27 '22 08:10

xk0der