Regular expression search in files, in the Visual Studio editor - visual-studio

I was trying to search for ".IsSet", but not "DocumentState.IsSet", in VS 2008 using regular expression search. How do I compose the regular expression?
Thanks!

Try
(?!<DocumentState)\.IsSet
The ?!< is a "negative lookbehind".

~(DocumentState)\.IsSet
will match all .IsSet instances that do not follow DocumentState. To match exactly .IsSet but not .IsSetFoo, you can either use
~(DocumentState)\.IsSet>
or check the Match whole word option.
See Regular Expressions (Visual Studio) for a list of regular expression tokens supported in the Visual Studio search.

Try this :
^\.IsSet
^ : means beginning of the string.

I don't know if you can with the VS Search, but you can
Replace DocumentState.IsSet by a token (like "DOCSTATE")
Replace all .IsSert
Replace your token "DOCSTATE" with DocumentState.IsSet

Related

Find and Replace on Visual studio with keeping the number

Is there way on visual studio to find and replace text but keeping the number in the string same?
For example, lets say I have a code that saids
fields[0].Value;
fields[1].Value;
And now I would like to replace it with
reader.GetString(0);
reader.GetString(1);
Without manually replacing every single lines of code, I was hoping to do it through find and replace dialog.
Is there any ways of doing this?
Thank you
If you want to replace part of the expression but keep a part (like the number in your case) you can use the search and replace function (ctrl+h) set to use regular expressions (alt+e) and use these expressions:
Search: fields\[(.)\].Value;
Replace: reader.GetString($1);
This will replace all expressions on the form fields[n].Value; with reader.GetString(n); where n is any single character. If you want to restrict it to keep numbers only use fields\[(\d)\].Value;
For more information see: Using Regular Expressions in Visual Studio
I tried it with VS2013 and it worked as expected.

Visual Studio 'Find and Surround With' instead of 'Find and Replace'

So i want to surround all string literals in our C++ source with an _T(...) for our unicode port.
This questions answers how I search for string literals but is there some way of surrounding the matched text with _T() instead of replacing with something else?
I intend to do it one string at a time anyway and not all at once but want to avoid having to type it out or use "Surround With" from Visual Assist myself for each string.
Jochen Kalmbach's answer might work in older versions of Visual Studio, but it didn't work for me in Visual Studio 2013. However, the small RegEx shortcut buttons to the right of the Find/Replace input boxes helped a lot:
In Find, select the ":q Quoted string" option.
In Replace, select the "$1 Substitute the substring matched by captured group number 1", and then surround $1 with _T().
Final Output
Find:
((\".+?\")|('.+?'))
Replace:
_T($1)
Note that the $1 represents the RegEx expression group enclosed in the outermost parentheses.
Here's another example:
Requirement
Find:
Converter.toCustomObject($find("Anything"));
Replace (different Converter method and add parameter after $find() parameter):
Converter.toDifferentObject($find("Anything"), true);
Solution
Find (use RegEx in Find options):
Converter\.toCustomObject\((\$find\(.*)\);
Replace:
Converter.toDifferentObject($1, true);
Notice that the Replace value doesn't need to escape special characters, though you can apply some RegEx, e.g. to add a Line Break after the output, you can use this for Replace:
Converter.toDifferentObject($1, true);\r\n
Goto: Edit|Find and Replace...|Quick Replace..
Then enter:
Find: :q
Replace with : _T(\0)
Use: Regular Expressions

Visual Studio macro to find a string and delete matching lines

In my Visual Studio (2010 C#) solution, I need to delete all lines of code that contain a matching string pattern.
For example, I want to delete all lines that contain ".BackColor = System.Drawing.Color.Yellow;". The Find and Replace feature of Visual Studio isn't good enough, because you cannot tell it to wipe out the matching lines.
So I think I would need a macro for that. Any help is appreciated.
You can use the "Find and Replace" feature of Visual Studio to delete matching lines.
The key is to match the whole line including the end of line character as well. You can do this in wildcard or regular expression mode. In wildcard mode, begin the expression with * and end the expression with *\n. The asterisks will match any number of characters, and the \n will match the end of line character.
In your case, your find query would be "*.BackColor = System.Drawing.Color.Yellow;*\n". The replace field should then be left blank.
To enable wildcard mode, select 'Wildcards' in the 'Use:' field of the 'Find options' section of the 'Find and Replace' dialog.
With Visual Studio 2015, 2017, 2019, 2022 this worked for me. Open Search window, check the "use regular expressions" checkmark. Fill "find what" with
.*myCodeFragmentHere.*\r?\n
fill "replace" with an empty string.
Remove all regexp (brackets, dots) from the code fragment in your search expression.
I tend to create macros in VS by running the macro recorder then editing the resulting code.
So, manually search for the pattern, and press F3. Stop the macro then (or press the line-start key, select to end of line, press delete and then stop the macro).
Edit the macro, the command to delete a line is:
DTE.ActiveDocument.Selection.SelectLine()
DTE.ActiveDocument.Selection.Delete()
You can set the find text with FindText:
DTE.ActiveDocument.Selection.FindText(".BackColor = System.Drawing.Color.Yellow;", vsFindOptions.vsFindOptionsFromStart)
Building upon #HolgerJeromin's answer: instead of guessing the right indentation match (could be tabs could be spaces could be more or less), I prefer matching the beginning of the line using the ^\s* pattern.
For example, to remove all lines having a ProducesResponseType attribute, I use
^\s*\[ProducesResponseType.*\n
(works on Windows too using VS 2019).
For Visual Studio 2015 (in which there are no macros and no wildcards), I did the following:
Open Find and Replace (Ctrl+H)
Set to use Regular Expressions (Alt+E)
Set the Find box to
({line of code string})\r?\n({next line tabbing})
Leave the Replace box empty
Replace
Where-
{line of code string} = the line of code you wish to remove. Note you need to escape characters such as parenthesis and quotes with a backward slash ()
{next line tabbing} = the number of spaces preceding the next line of code (without this your line will be removed but the next line would have double the spaces before it
For example, to remove
DoSomething("hello");
From -
class A
{
void SomeMethod()
{
DoSomething("hello");
DoSomethingElse();
}
}
Replace the following
(DoSomething(\"hello\")\;)\r?\n({ })
I was trying to remove an attribute ([OperationContract] in my case) and none of the other answers worked for me. I finally got it to work by using the following:
\[OperationContract\]\r\n\t\t (Use Regular Expressions)

Visual Studio 2008: Find and Replace with new line character?

Sometimes i would like to search for text containing a new line character and there are other times i would like to replace text with a new line character.
How can i do this with visual studio 2008?
Use a RegEx search:
In the Find Dialog - Expand "Find Options"
Check the box for Use: Regular Expressions
Next to the search box there is now an arrow that is active, it will show you available RegEx options/values.
The value you want will be \n. So "SearchValue\n" should do it.
Be aware that that its not a standard RegEx that you use, it's VS specific.
Replace can also use the RegEx values.
Adding on to Brian Schmitt's answer...
Regular expression searches using \n work as expected. However you have to be a little careful when using \n in regex replaces with Visual Studio 2008. For example, if you search for \n and replace with \n (yes, the exact same thing) all of the line breaks in your file(s) will be converted to Unix-style newlines (LF). This may be a bug in Visual Studio. I find it hard to believe this is the intended functionality.
To get around this, you can use tagged expressions, using curly braces: e.g. search for SearchValue{\n} and replace with ReplaceValue\1. This ensures that the same line-break character(s) that were found when searching will also be used when replacing.
You can try my Multiline Search and Replace Macro.

Regex to search for a word in a string in Visual Studio

I need to search all of my codebase for "Url" and replace it with "URL". If I search for Url in Visual Studio I also get all my variables with "Url" in it.
Anyone have a Regex I can use to only find Url within a quoted string e.g. "Use this Url:"?
Edit
I was looking looking for a quick and dirty way to find designer text and hard coded strings that had Url in the string and change them to URL.
What I really ended up needing was:
("[^"]*Url[^"]*")
And thanks to the tip from tghw who pointed out the :q shortcut in Visual Studio equates to:
(("[^"]*")|('[^']*'))
I realized I needed to use the first portion to find only the double quoated strings I was looking for.
Both this regex and a standard find with 'Match case' and 'Match whole word' yielded results with some strings I was hoping to not find but eliminated the code with 'Url' in it.
Visual Studio has a "quoted string" operator :q. If you search for :qUrl with 'Use: Regular expressions' and 'Match case' on, it should find all instances of "Url" only in strings.
Update: The above is incorrect. :q just searches for a quoted string, but you can't put anything into it. My testing was just showing cases that looked correct, but were just coincidentally correct. I think instead, you want something like:
^(:q*.*)*(("[^"]*Url[^"]*")|('[^']*Url[^']*'))(:q*.*)*$
If you just quickly want to search for a quoted string you can use the "Use Wildcards" Find Option in Visual Studio.
For example:
"*Url*"
I used the following to search only "whole words" (i mean: appearing with an space before an after or immedately after or before the " ):
(("[^"]*[ ]|")Url([ ][^"]*"|"))
For example this matches "test Url" and "Url test" but don't "testUrl".
"Use this (Url):", then you can replace $1 (or whatever syntax Visual Studio uses). You may need to escape the quotes, and I'm not sure if Visual Studio lets you parenthesize parts of the regex.

Resources