C# Find and Replace a section of a string with wildcard type search using RegEx (while retaining som

Posted by fraXis on Stack Overflow See other posts from Stack Overflow or by fraXis
Published on 2010-05-10T00:29:58Z Indexed on 2010/05/10 0:38 UTC
Read the original article Hit count: 312

Filed under:
|
|
|
|

Hello,

I am trying to replace some text in a string with different text while retaining some of the text and I am having trouble doing it.


My code is:

StreamReader reader = new StreamReader(fDialog.FileName.ToString());
string content = reader.ReadToEnd();
reader.Close();

/Replace M2 with M3 (this works fine)
content = Regex.Replace(content, "M2", "M3");


I want to replace a string that contains this:

Z0.1G0H1E1

and turn it into:

G54G43Z.1H1M08
(Note the Z value and the H value contain the same numeric value before the text change)


The trouble I am having is that when I replace the values, I need to retain the H value and the Z value from the first set of text.


For example,

Z0.5G0H5E1

I need to add the new text, but also add the H5 and Z0.5 back into the text such as:

G54G43Z0.5H5M08


But the Z values and H values will be different every time, so I need to capture those values and reinsert them back into the string when add the new G54G43 values.


Can someone please show me how to do this using Regex.Replace?

Thanks so much, Shawn

© Stack Overflow or respective owner

Related posts about c#

Related posts about find