简体   繁体   English

在Visual Studio中搜索和替换

[英]Search and replace in Visual Studio

In Visual Studio, when I search within a selection, I want to replace the first instance (or second, third, etc.) of a match per line using regular expressions. 在Visual Studio中,当我在选择中进行搜索时,我想使用正则表达式替换每行匹配项的第一个实例(或第二个,第三个等)。 How would I do this? 我该怎么做?

Search and replace 搜索并替换

foo1 = foo1;
foo2 = foo2;
...
foo20 = foo20;

into the following. 进入以下。

foo1 = bar1;
foo2 = bar2;
...
foo20 = bar20;

In Visual Studio 2012, capture groups and backreferences are used just like in C#. 在Visual Studio 2012中,捕获组和反向引用的用法与C#中的用法相同。 You can capture them with common parenthesis, and backreference them with $0, $1, etc. Hope it helps! 您可以使用通用括号捕获它们,并使用$ 0,$ 1等向后引用它们。希望对您有所帮助!

Note that the syntax $1 is used for find-replace, but \\1 is used for backreferences in the search string. 请注意,语法$1用于查找替换,而\\1用于搜索字符串中的向后引用。

In Visual Studio 2010 and earlier , use regular expressions with back references Visual Studio 2010和更早版本中 ,将正则表达式与反向引用一起使用

Visual Studio's regular expressions are completely different from what I've learned. Visual Studio的正则表达式与我所学的完全不同。 Took me some time to figure out the correct answer. 花了我一些时间找出正确的答案。

Search for 搜索

{foo}{:d+} = \1\2

Replace with 用。。。来代替

\1\2 = bar\2

Back references are done by tagging with curly braces {foo} . 通过使用大括号{foo}进行tagging来完成后向引用。 :d+ is the same for \\d+ :d+\\d+相同

Read more about VS RegEx here 在此处阅读有关VS RegEx的更多信息

Here it is, type exactly as it is displayed here 在这里,完全按照此处显示的方式键入

Search: (\\w+\\d+\\s*=\\s*)[^\\d]+(\\d+); 搜索: (\\w+\\d+\\s*=\\s*)[^\\d]+(\\d+);

Replace: $1bar$2; 替换: $1bar$2;


Read more: Using Regular Expressions in Visual Studio 阅读更多: 在Visual Studio中使用正则表达式

As simple as this in Visual Studio 2019 Find/Replace. 在Visual Studio 2019查找/替换中如此简单。 I needed to replace FORTRAN IO format string to C++ format and used sub-expression and numbers of regexp. 我需要将FORTRAN IO格式的字符串替换为C ++格式,并使用子表达式和正则表达式的编号。

Example: find: "f9.8", "f18.3", in line and replace with %9.8f, %18.3f 示例:找到:“ f9.8”,“ f18.3”,并用%9.8f,%18.3f替换
reg exp: Find = ( f)(\\d+.\\d+) Replace = %$2f reg exp:查找=(f)(\\ d +。\\ d +)替换=%$ 2f

I can be done without a regular expression as well: 我也可以不用正则表达式来完成:

Replace = foo with = bar . = bar替换= foo

If a regular expression is needed, one could use: 如果需要一个正则表达式,则可以使用:

foo(\d*) = foo(\d*);

Replace with: 用。。。来代替:

foo\1 = bar\2;

If you would be more variable: 如果您的变量更大:

Regex.Replace(input, @"(?<=\= )[^;0-9]*(?=[0-9]*;)", replacewith);

This search for = and (anynumber); 此搜索=(anynumber); and replace that between. 并在两者之间替换。

Edit: The number is optional. 编辑:该数字是可选的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM