查找并替换字符串,但在原处保留几个字符

Find and Replace String but Keep a few Characters In Their Place

我有一个字符串,例如

thisIsAString.property = thisIsAMethod.doThis(yyy);

我想替换为

thisIsAString.aDifferentProperty = ((thisIsAString.property = thisIsAMethod.doThis(yyy)) != string.Empty) ? true : false;

其中 yyy 在替换期间将保持不变,但会针对我项目中的每个文档进行更改。

因此在我的“查找和替换”工具栏中,框将包含以下内容:

查找内容: thisIsAString.property = thisIsAMethod.doThis(SOME REGEX??);
替换为: thisIsAString.aDifferentProperty = ((thisIsAString.property = thisIsAMethod.doThis(REGEX TO KEEP WHAT WAS IN HERE IN 'FIND WHAT')) != string.Empty) ? true : false;
查看: Current Project

我会全部替换

我可以在 Visual Studio 2013 年使用 编辑 -> 查找和替换 -> 在文件中替换 吗?

您需要捕获您想要保留的部分并使用反向引用将其放回:

Find: thisIsAString.property = thisIsAMethod.doThis\((.*?)\);
Replace: thisIsAString.aDifferentProperty = ((thisIsAString.property = thisIsAMethod.doThis()) != string.Empty) ? true : false;

这里的重要部分是;

  • 使用(.*?) 捕获 "YYY"
  • 使用 ,它指的是 "group 1",将其包含在替换中
  • 转义查找词中的文字括号

这是我可以想出的正则表达式替换:

(?m)^\s*(?<astr>\w+)\.(?<prop>\w+)\s*=\s*(?<mthd>\w+)\.(?<dothis>\w+)\((?<inbr>.*?)\);\s*\r?$

替换字符串为:

${astr}.aDifferentProperty = ((${astr}.${prop} = ${mthd}.${dothis}(${inbr})) != string.Empty) ? true : false;

demo

如果\w+不匹配,用字符class调整,例如[\w.] 也匹配一个点。