VisualStudio 中的多行查找和替换

能做到吗? 我们使用 VS2005VS2008VS2010

我不是指正则表达式(它们有自己的位置) ,而是指寻找和替换普通的旧文本。我知道我们可以(在必要时)使用 N标记来实现正则表达式,但是我们不希望在正则表达式转义字符中纠缠在一起,另外还有一个可读性问题。

如果做不到,人们还有什么简单(免费)的选择?这不包括搞砸我们自己的宏。

60988 次浏览

I finally found it...

There isn't any need to download and load any external macro.

It’s working in Visual Studio 2008 with in-built macro at least. :)

Steps:

  1. Select text you want to find.
  2. Press Alt + F8 or open "Tools -> Macros -> Macro Explorer"
  3. Double click SampleUtilitiesFindLine. (It will open the Find box with your selection loaded in the "Find" field. Don't worry about truncated text shown in the "Find" field. Trust me, the field has it all... The Microsoft way of showing it may be... :) )
  4. Click on the "Quick Replace" button in the "Find And Replace" dialog box. Enter your replace with text.
  5. And click any of three buttons as per your requirement...and it’s done. :)

Hurray... it’s working. It may not be a straightforward way to do it, but you know with Microsoft. Nothing is straightforward and easy.. :)

You could also open the files with UltraEdit which fully supports MultiLine replace. You can use the trial version if you only intend to use it once.

You can search for multiline expressions by clicking on the "Use Regular Expressions" checkbox in the "Find and Replace" dialog. Line breaks are then indicated by \n.

enter image description here

This works today in Visual Studio 2012:

fooPatternToStart.*(.*\n)+?.*barPatternToEnd

See how the (.*\n)+? part does the match across multiple lines, non-greedy.
fooPatternToStart is some regex pattern on your start line, while barPatternToEnd is your pattern to find on another line below, possibly many lines below...

Example found here.

Simple and effective :)

Note: before VS2012, the pattern that worked was: fooPatternToStart.(.\n)+@.*barPatternToEnd

Regarding the comment of Andrew Corkery:

If you like to specify a multi-line replacement string as well, edit the macro code and set the replacement text as shown below. This will allow you to "fine-tune" your replacement with just the small modifications needed.

Sub FindLine()
Dim textSelection As TextSelection


textSelection = DTE.ActiveDocument.Selection
textSelection.CharLeft(True)
DTE.ExecuteCommand("Edit.Find")
DTE.Find.FindWhat = textSelection.Text


' Also preset replacement text with current selection
DTE.Find.ReplaceWith = textSelection.Text
End Sub

It’s provided by Microsoft only. Please check Multiline Search and Replace.

It uses regular expression only. But for those who don't know regex, it is better to use it.

The latest version (as of this posting) of Notepad++ does multi-line find/replace. With no macro support in Visual Studio any more, this is relevant now.