[英]C# Regex Replace with parts of the same string
我正在嘗試替換生成的代碼文件的一部分:
public System.Nullable<int> SomeInt { get; set; }
public System.Nullable<bool> SomeBool { get; set; }
public System.Nullable<bool> SomeOtherBool { get; set; }
我想要得到的是:
public int? SomeInt { get; set; }
public bool? SomeBool { get; set; }
public bool? SomeOtherBool { get; set; }
我知道代碼是等效的,后者只是語法糖。 但是我還是想這樣做,因為它更具可讀性。
regex模式很容易編寫,
System\.Nullable<.*>
對於整個事情,諸如此類
(?<=System\.Nullable<).*(?=>)
以獲得內部的原始類型。 但是我無法終生搞清楚如何使用C#的Regex API正確實現替換。
將Regex.Replace
與命名捕獲組配合使用將起作用:
string replaced = Regex.Replace(src, @"System\.Nullable<(?<type>.*)>", "${type}?");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.