News


One of the blogs I read is Zain Naboulsi’s Visual Studio Tips and Tricks. In a recent post he discussed the power of using Find and Replace with regular expressions and it gave me an idea about how to quickly reverse a set of assignment statements.

Lets say you have the following code:

Me.FirstNameTextBox.Text = customer.FirstName
Me.LastNameTextBox.Text = customer.LastName
Me.TelephoneTextBox.Text = customer.Telephone
Me.EmailTextBox.Text = customer.Email 

And you want to reverse the assignments so that you are writing the textboxes back into the customer object (generally the next thing you would want to do). Rather than doing it by hand, or using some macro, you can use the find and replace window with a regular expression:

FindAndReplace

This works because the expression matches any character (.) zero or more times (*), followed by an equals sign then any character zero or more times. In other words, anything followed by “=” followed by anything. The two anythings in the expression are enclosed with curly brackets to make them tagged expressions, which means they can be used in the replace expression. \1 will be the first tagged expression, \2 then next and so on. So our replace with expression just says replace a=b with b=a.

So what do you end up with? Well, this of course:

customer.FirstName = Me.FirstNameTextBox.Text
customer.LastName = Me.LastNameTextBox.Text
customer.Telephone = Me.TelephoneTextBox.Text
customer.Email = Me.EmailTextBox.Text

kick it on DotNetKicks.com

Comments

Gravatar # re: Reversing assignment statements with Find and Replace in VS 2010
Posted by Gary Woodfine on 9/15/2010 3:57 PM
Awesome tip thank you. I have never actually thought about using that before, but after I read your post it completely made sense to do it. Like you say if you are doing any type of Automapper stuff, or reassignment statements this can become quite tedious!
Gravatar # re: Reversing assignment statements with Find and Replace in VS 2010
Posted by Paul Batum on 9/23/2010 4:16 PM
Resharper has a reverse assignment quickfix.
Gravatar # re: Reversing assignment statements with Find and Replace in VS 2010
Posted by Darren Fieldhouse on 9/24/2010 3:46 AM
There are loads of tools to do this, including many macros, but I really liked this light weight, build-in solution.
Gravatar # re: Reversing assignment statements with Find and Replace in VS 2010
Posted by Leyu Sisay on 9/24/2010 4:58 AM
Handy if you don't have Resharper :-)
Gravatar # re: Reversing assignment statements with Find and Replace in VS 2010
Posted by Don on 9/27/2011 11:21 AM
if you're in c# it should be more like this:

{.*}={.*};

\2 = \1;

That will take care of the semicolons.
Post A Comment
Title:
Name:
Email:
Comment:
Verification: