【问题标题】:Visual Studio 2017 - Find and replace with textVisual Studio 2017 - 用文本查找和替换
【发布时间】:2018-01-19 14:51:17
【问题描述】:

我在一个类中有这个属性:

public string fooo { get; set; }

我需要用类似的方式重写它:

[BsonElement("fooo")] 
public string fooo{ get; set; }

我必须为很多属性这样做,所以我想在 Visual Studio 中使用“查找替换功能”。

我使用以下宏:

Search : public 
Replace : [BsonElement("")]\n\t\tpublic 

如何使用正则表达式动态获取fooo 名称并将其放入BsonElement 属性中?在全球范围内,是否有可能提供有关此文档的链接,尚未找到。

【问题讨论】:

标签: c# regex visual-studio


【解决方案1】:

这里有一个解决方案,适用于格式为 public string fooo { get; set; } 的属性(空格很重要:单行,属性名称后有空格)

搜索:

(public) (\w+) (\w+) { get; set; }

替换:

[BsonElement("$3")]\n\t\t$1 $2 $3 { get; set; }

解释:

$1$2$3 是在() 中捕获的组

\w 等价于[a-zA-Z0-9_],所以(\w+) 将匹配任何类型名称和属性名称

【讨论】:

  • 我怎么可能在第一个 w+ 中排除 class 而在第二个 w+ 中包含 ? . < >
  • 排除class:((?!class)\w+)(负前瞻);包括运算符:([\w?.<>]+)
【解决方案2】:

查找:(\s*)public string (\w+) { get; set; }

替换:$1[BsonElement("$2")]\n$1public string $2{ get; set; }

此解决方案保留定义前的空格(制表符等)

Image for your convenience

【讨论】:

    【解决方案3】:
    1. 打开查找和替换(Ctrl + H)
    2. public (\w+) (\w+) { get; set; } 粘贴到“查找”字段中。
    3. [BsonElement("$2")]\n\t\t public $1 $2 { get; set; } 粘贴到替换字段中。
    4. 启用正则表达式(Alt+E)。
    5. 全部替换(Alt+A)。或者有选择地一一进行。

    但请注意,如果您有一些其他关键字,例如 virtualstatic 等,您将需要更多地捕获组并更改索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-06
      • 2010-10-23
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 2014-10-29
      相关资源
      最近更新 更多