Visual Studio Find and Replace Regular Expressions

2020-02-17 06:08发布

问题:

I'd like to replace some assignment statements like:

int someNum = txtSomeNum.Text; 
int anotherNum = txtAnotherNum.Text;

with

int someNum = Int32.Parse(txtSomeNum.Text);
int anotherNum = Int32.Parse(txtAnotherNum.Text);

Is there a good way to do this with Visual Studio's Find and Replace, using Regular Expressions? I'm not sure what the Regular expression would be.

回答1:

I think in Visual Studio, you can mark expressions with curly braces {txtSomeNum.Text}. Then in the replacement, you can refer to it with \1. So the replacement line would be something like Int32.Parse(\1).


Update: via @Timothy003

VS 11 does away with the {} \1 syntax and uses () $1



回答2:

Comprehensive guide

http://blog.goyello.com/2009/08/22/do-it-like-a-pro-%E2%80%93-visual-studio-find-and-replace/



回答3:

This is what I was looking for:

Find: = {.*\.Text}

Replace: = Int32.Parse(\1)



回答4:

Better regex for the original problem would be

find expr.: {:i\.Text}

replace expr.: Int32.Parse(\1)

Check out: http://msdn.microsoft.com/en-us/library/2k3te2cs%28v=vs.100%29.aspx

for the definitive guide to regex in VS.

I recently completed reformatting another programmer's C++ project from hell. He had completely and arbitrarily entered, or left out at random, spaces and tabs, indentation (or not), and an insane level of parentheses nesting, such that none of us used to coding standards of any type could even begin to read the code before I started. Used regex extensively to find and correct abnormal constructs. In a couple of hours, I was able to correct major problems in approximately 125,000 lines of code without actually looking at most of them. In one particular single find/replace I changed more than 22,000 lines of code in 125 files, total time under 10 seconds.

Particularly useful constructs in the regex:

:b+ == one or more blanks and/or tabs.

:i == matches a C-style variable name or keyword (i.e. while, if, pick3, bNotImportant)

:Wh == a whitespace char.; not just blank or tab

:Sm == any of the arithmetic symbols (+, -, >, =, etc.)

:Pu == any punctuation mark

\n == line break (useful for finding where he had inserted 8 or 10 blank lines)

^ == matches start of line ($ to match end)

While it would have been nice to match some other regex standard (duh), I did find a number of the MS extensions extremely useful for searching a code base, such as not having to define 'identifier' hundreds of times as "[A-Za-z0-9]+", instead just using ":i".