1

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,

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.

3
  • Are you using Visual Studio search/replace? If so, which version of VS, because they changed the regex syntax as of VS2012 Commented Aug 13, 2014 at 14:20
  • Have you tried, Regex.Replace()? Commented Aug 13, 2014 at 14:21
  • No, I'm generating source files using CodeDom, and then reading the files and performing replace on them using the Regex API. This is all done from code. Commented Aug 13, 2014 at 14:23

1 Answer 1

1

Using Regex.Replace with a named capture group would work:

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

Example: https://dotnetfiddle.net/GWsKlf

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.