This question already has an answer here:
I have a bunch of assignment operations in Visual Studio, and I want to reverse them: i.e
i = j;
would become
j = i;
i.e. replacing everything before the equals with what's after the equals, and vice versa
Is there any easy way to do this, say something in the regular expression engine?
Cheers, Ed
Unfortunatly I don't have Visual Studio, so I can't try in the target environment, but if it uses standard regexps, you could probably do it like this: Search for "
(:Al) = (:Al);
", and replace with "\2 = \1
". (\1 and \2 are references to the first and second capture groups, in this case the parenthesises around the \w:s)EDIT
Ok, not \w... But according to MSDN, we can instead use :Al. Edited above to use that instead.
Also, from the MSDN page I gather that it should work, as the references seem to work as usual.
The robust way to do this is to use a refactoring tool. They know the syntax of the language, so they understand the concept of "assignment statement" and can correctly select the entire expression on either side of the assignment operator rather than be limited to a single identifier, which is what I think all the regular expressions so far have covered. Refactoring tools treat your code as structured code instead of just text. I found mention two Visual Studio add-ins that can do it:
(Inverting assignment isn't technically refactoring since it changes the behavior of the program, but most refactoring tools extend the meaning to include other generic code modifications like that.)
In Visual Studio 2015+ after selecting code block press
Ctrl + H
:Find:
(\w+.\w+) = (\w+);
Replace:
$2 = $1;
For example:
changes to:
what about replace all (CTRL-H)
you can replace for example "i = j;" by "j = i;"
you can use regular expressions in that dialog. I'm not so sure about how you should pop-up help about them however. In that dialog, press F1, then search that page for more information on regular expressions.
I like this dialog because it allows you to go through each replacement. Because the chance of breaking something is high, I think this is a more secure solution
Just a slight improvement on Chris's answer...
Ctrl+H, then replace:
with:
(better handling of whitespace, esp. at beginning of line)
EDIT: For Visual Studio 2012 and higher (I tried it on 2015): Replace
with:
You can do search and replace with regular expressions in Visual Studio, but it would be safer to just do a normal search and replace for each assignment you want to change rather than a bulk change.