C#Regex替换为相同字符串的部分

时间:2014-08-13 14:13:05

标签: c# regex

我正在尝试替换生成的代码文件的一部分:

    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; }

我知道代码是等价的,后者只是语法糖。但无论如何我想要这样做因为它更具可读性。

正则表达式模式很容易编写,

System\.Nullable<.*>

整个事情,像

(?<=System\.Nullable<).*(?=>)

获取内部的原始类型。但我不能为我的生活弄清楚如何使用C#的Regex API来正确实现替换。

1 个答案:

答案 0 :(得分:1)

Regex.Replacenamed capture group一起使用会起作用:

string replaced = Regex.Replace(src, @"System\.Nullable<(?<type>.*)>", "${type}?");

示例: https://dotnetfiddle.net/GWsKlf

相关问题