Regular Expression question Visual Studio
I'm wanting to replace all references to a resource file in my C# code.
An example is a page that contains several references such as:
Resources.Global.Firstname
Resources.Global.Surname
I'd like the regular expression to find all of these (they could end either with a ;
or a )
).
开发者_运维百科Total beginner with regular expressions, so any advice here would be gratefully received.
You can just use the Find and Replace window in Visual Studio.
- Press Ctrl-H to open the window.
- Put
Resources\.Global\.{[^,) ;]+}
in the "Find what:" text box. - Put
GetStringValue("\1")
in the "Replace with:" text box. - Make sure the "Look in:" dropdown is set to the scope you want to search
- Expand the Find options subpanel.
- Check the box next to "Use:" and make sure that "Regular expressions" is selected.
What this is doing:
The first regular expression will find anything that starts with Resources.Global.
and capture whatever is after it until it finds a space, a comma, a close paren, or a semi-colon.
The second one replaces the entire text that was found with GetStringValue("")
and puts the captured text inside the quotes in the parentheses.
Why not just do CTRL+H (quick find and replace) and search on the actual terms rather than the regex pattern? What are you trying to rename from and to?
UPDATE The pattern to match would be something like: Resources.Global.([^};]+)
Replace pattern would be GetStringValue("\1")
As Blazes said, in the scenario you mentioned, Refactoring is the actual answer. If you just want to see them, right click on the definition and select Find all references. If you want to change it, just make the changes and then press ctrl+shift+F11, a context menu appears which gives you the chance to rename all references.
Regular expression:
(Resources\.Global\.[A-Z][a-zA-Z]*[;\)])
will find only the last two lines out of the following tested lines:
Resources.Global.Firstname
Resources.Global.Surname
Resources.Global.Firstname;
Resources.Global.Surname)
used code to verify:
Regex regex = new Regex(@"(Resources\.Global\.[A-Z][a-zA-Z]*[;\)])");
MatchCollection mc = regex.Matches("Resources.Global.Firstname\n" +
"Resources.Global.Surname" +
"Resources.Global.Firstname;" +
"Resources.Global.Surname)");
foreach (Match match in mc)
{
Console.WriteLine(match.Groups[1].ToString());
}
This software might help you:
Rad Software Regular Expression Designer
精彩评论