![]() |
Platforms, Frameworks & Libraries »
.NET Framework »
General
Intermediate
Replace text using tagged expressionsBy Michel.SmitsAn article on how to replace text using regular expressions, in the VS.NET IDE. |
Windows, .NETVS.NET2003, VS2005, Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
Visual Studio has a very powerful search and replace feature, which is the "tagged expression". You can search and replace using regular expressions, keeping groups of content intact. This can be useful in stuff like refactoring or simply reformatting code.
A tagged expression is used to identify a piece of text so it can be used in the replacement. You identify a tagged expression with "{" and "}". You can use as many of those as you want.
If you enter the following in the replace dialog:
Find what:
{ content }
Replace with:
\1
You are replacing the group containing "content" with the same.
The following entry will replace the selection with the same:
Find what:
{.*}
Replace with:
\1
Just to be clear, a picture of the dialog:

OK, I admit, so far it doesn't look very useful. However, from this starting point, you can use any expression to split up text in parts and reassemble them.
Here's a hopefully more interesting example of what you can do:
Given below is an SQL connection string property value after dragging a data source in the designer:
workstation id=LEBOWSKI;packet size=4096;
user id=sa;data source=LEBOWSKI;
persist security info=True;
initial catalog=TheInternet;password=protected
If I replace:
Find what:
{[^=]*}={[^;]*};
Replace with:
options.Add("\1", "\2");\n
You'll get the following:
options.Add("workstation id", "LEBOWSKI");
options.Add("packet size", "4096");
options.Add("user id", "sa");
options.Add("data source", "LEBOWSKI");
options.Add("persist security info", "True");
options.Add("initial catalog", "TheInternet");
options.Add("password", "protected");
Note: "[^=]" means any character except "=", and "*" means as many as there are.
This may not be a sample you will use yourself, but I hope to have shown you the power of what you can do. And hopefully you'll start using it yourself.
For an overview of the expression syntax, click on the Help button in the Replace dialog. Thanks for reading!
| You must Sign In to use this message board. | |||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 2 Feb 2006 Editor: Smitha Vijayan |
Copyright 2006 by Michel.Smits Everything else Copyright © CodeProject, 1999-2009 Web21 | Advertise on the Code Project |