简体   繁体   English

C#正则表达式用相同字符串的部分替换

[英]C# Regex Replace with parts of the same string

I'm trying to replace parts of a generated code file: 我正在尝试替换生成的代码文件的一部分:

    public System.Nullable<int> SomeInt { get; set; }

    public System.Nullable<bool> SomeBool { get; set; }

    public System.Nullable<bool> SomeOtherBool { get; set; }

What I'm trying to get is this: 我想要得到的是:

    public int? SomeInt { get; set; }

    public bool? SomeBool { get; set; }

    public bool? SomeOtherBool { get; set; }

I know the code is equivalent, with the latter being just syntactic sugar. 我知道代码是等效的,后者只是语法糖。 But I want to do it anyway cause it's more readable. 但是我还是想这样做,因为它更具可读性。

The regex patterns are easy enough to write, regex模式很容易编写,

System\.Nullable<.*>

for the whole thing, and something like 对于整个事情,诸如此类

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

to get just the primitive type inside. 以获得内部的原始类型。 But I can't for the life of me figure out how to use C#'s Regex API to implement the replacement correctly. 但是我无法终生搞清楚如何使用C#的Regex API正确实现替换。

Using Regex.Replace with a named capture group would work: Regex.Replace命名捕获组配合使用将起作用:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM