查找并替换字符串,但保留一些字符

时间:2015-08-12 20:49:06

标签: regex visual-studio-2013 replace find

我有一个字符串,如

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中执行此操作吗?查找和替换 - >替换文件

2 个答案:

答案 0 :(得分:1)

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

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

这里的重要部分是;

  • 使用(.*?) 捕获“YYY”
  • 使用\1(引用“第1组”)将其包含在替换
  • 转义查找字词
  • 中的字面括号

答案 1 :(得分:0)

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

(?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+不匹配,请使用字符类进行调整,例如[\w.]也匹配一个点。