I’ve got the following string:
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")]
I need to alter it to look like the following:
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("myClass", "myVersion")]
The simplest way to achieve this, obviously, is to use a Regex to capture the pieces that I want from that string, and then concatenate the results with my extra text. However I’m looking to use the Regex.Replace() method to make the code a bit cleaner:
Regex generatedCodeAttributeRegex = new Regex("\\[[?:global::|]System.CodeDom.Compiler.GeneratedCodeAttribute\\((\"System.Data.Design.TypedDataSetGenerator\",[\\s+]\"2.0.0.0\")\\)\\]");
inputFileContent = generatedCodeAttributeRegex.Replace(inputFileContent, delegate(Match m)
{
return string.Format("\"{0}\", \"{1}\"",
this.GetType(),
Assembly.GetExecutingAssembly().GetName().Version);
});
From my understanding, this should replace the captured group with the text specified in the delegate… the problem is that it doesn’t. What am I doing wrong? And is it possible to achieve this with the Regex.Replace(string, string) overload?
Your regex does not match because you wrote
[?:global::|], which is a character range containing the characters ?, :, g, l, o, b, a, :, and |. You probably meant(?:global::|)which is the same as(?:global::)?, i.e. “global:: or nothing”.Also note that by not escaping the dots, they will match anything – not just literal dots. Though that is unlikely to cause problems.
If you fix that, it will work, but not quite as you want, since Regex.Replace replaces the whole match, not just the part in the capturing group.