在VisualStudio 编辑器文本替换中使用正则表达式

替换时使用正则表达式,其优点在于可以通过正则分组捕获,并在替换字符串中使用。

在VS2012之前的版本中,捕获内容用{}包含,引用时,使用 \1 形式;

在VS2012及以后版本中,捕获内容符合正则表达式,用()包含,引用时使用 $1 形式。

下面以新版本格式举例说明:

假设代码中包含多个自动属性,如

1 public bool IsChecked { get; set; }
2 public double Width { get; private set; }
3 private int Count { get; set; }

假设所在类型实现INotifyPropertyChanged接口,且有方法

1 void RaisePropertyChangedEvent(string PropertyName){
2     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
3 }

现在要为所有公共属性添加相应的私有字段,使其能在赋值变更时调用函数触发属性通知事件,则可在Ctrl + h唤出替换窗口,并启用正则表达式。

在源文本框中输入:

  public (\S*) (\S*) { get; (\S*\s?)set; }

在替换目标文本框中输入:

  public $1 $2 { get { return _$2; } $3set { _$2 = value; RaisePropertyChangedEvent("$2"); } } $1 _$2;

在匹配文本中,每个分组用小括号()包含,并从1开始捕获。标记为红色的为属性类型标记为绿色的为属性名标记为紫色的为set访问器修饰符

在目标文本中,被捕获的文本用美元符号$和1基索引值代表,替换后的代码为每个公共属性增加了一个私有字段,该字段名为在属性名前加上一个下划线_。

1 public bool IsChecked { get { return _IsChecked; } set { _IsChecked = value; RaisePropertyChangedEvent("IsChecked"); } } bool _IsChecked;
2 public double Width { get { return _Width; } private set { _Width = value; RaisePropertyChangedEvent("Width"); } } double _Width;
3 private int Count { get; set; }

 

posted @ 2017-01-01 01:07  崩溃侠  阅读(1357)  评论(0编辑  收藏  举报
友情链接: Heroius' Ideas 沈阳因斯福环保安全科技有限公司 东北大学工业爆炸防护研究所