A.R.
A.R.

Reputation: 15705

Exclude comments when searching in Visual Studio

Is there a way to perform searches (Find / Find in Files) in visual studio that will exclude matches in comments? While sometimes it is useful, other times it is the opposite. For all of the options presented, I figured it would be in there, but I can't find it if it is.

I am using VS 2010/2012 about equally by the way.

Upvotes: 74

Views: 22916

Answers (4)

Pingui
Pingui

Reputation: 1496

You probably mean any comments, both single- (//) and MULTI-LINE (/**/).

The other answers only deal with single-line-comments. So here comes my VS Code-compatible Regex for both of them at the same time:

(?<!//.*)(?!(/\*).*)YOUR_SEARCH_TERM(?![^/\*]*?\*/)

Explanation:

(?<!//.*) is a negative look-behind against single-line-comments (//)

(?!(/\*).*) invalidates your search term if it is preceded by /*

(?![^/\*]*?\*/) invalidates your search term if it is followed by */ (short of a /* between your search term and itself, because then your search term would be outside of /**/ and you want it to be matched again).

To use it in VS Code, just type Ctrl + F and tick the regex-icon in the search-field popping up (with void being your exemplary search term):

enter image description here

Upvotes: 2

Jared Thirsk
Jared Thirsk

Reputation: 1356

Here's the regex that works for me for newer versions of Visual Studio:

^(?![ \t]*//).*your_search_term

Note that the syntax changed as of VS 2012:

Visual Studio 2012 uses .NET Framework regular expressions to find and replace text. In Visual Studio 2010 and earlier versions, Visual Studio used custom regular expression syntax in the Find and Replace windows.

Reference: https://msdn.microsoft.com/en-us/library/vstudio/2k3te2cs(v=vs.110).aspx

Upvotes: 61

LZH
LZH

Reputation: 785

you could try the regex as below:

^~(:b*//).*your_search_term

Short explanation:

  • ^ from beginning of line
  • ~( NOT the following
  • :b* any number of white spaces, followed by
  • // the comment start
  • ) end of NOT
  • .* any character may appear before
  • your_search_term your search term :-)

saw this at another post.

Upvotes: 26

David Mason
David Mason

Reputation: 1595

I don't believe it's an option in VS. You could try regular expressions, but those are limited by how creative you can be. It seems like it would be not entirely difficult to search for lines not beginning with // using a regex.

Upvotes: 1

Related Questions