Search and replace in Visual Studio

后端 未结 6 815
遥遥无期
遥遥无期 2020-12-29 03:52

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. How would I

相关标签:
6条回答
  • 2020-12-29 03:58

    I can be done without a regular expression as well:

    Replace = foo with = bar.

    If a regular expression is needed, one could use:

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

    Replace with:

    foo\1 = bar\2;
    
    0 讨论(0)
  • 2020-12-29 03:59

    In Visual Studio 2012, capture groups and backreferences are used just like in C#. You can capture them with common parenthesis, and backreference them with $0, $1, etc. Hope it helps!

    Note that the syntax $1 is used for find-replace, but \1 is used for backreferences in the search string.

    0 讨论(0)
  • 2020-12-29 04:02

    Here it is, type exactly as it is displayed here

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

    Replace: $1bar$2;


    Read more: Using Regular Expressions in Visual Studio

    0 讨论(0)
  • 2020-12-29 04:05

    If you would be more variable:

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

    This search for = and (anynumber); and replace that between.

    Edit: The number is optional.

    0 讨论(0)
  • 2020-12-29 04:07

    In Visual Studio 2010 and earlier, use regular expressions with back references

    Visual Studio's regular expressions are completely different from what I've learned. 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}. :d+ is the same for \d+

    Read more about VS RegEx here

    0 讨论(0)
  • 2020-12-29 04:12

    As simple as this in Visual Studio 2019 Find/Replace. I needed to replace FORTRAN IO format string to C++ format and used sub-expression and numbers of regexp.

    Example: find: "f9.8", "f18.3", in line and replace with %9.8f, %18.3f
    reg exp: Find = ( f)(\d+.\d+) Replace = %$2f

    0 讨论(0)
提交回复
热议问题