Find and Replace a section of a string with wildcard type search using RegEx (while retaining some text)
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?
If the string contains nothing but the serial number (?), it is easiest to extract the parameters one by one, and building them into a string. (you may want to create a function for the Regex.Match
lines, they are almost identical). This version doesn't assume any order between Z and H:
string s = "Z0.5G0H5E1";
string zValue = Regex.Match(s, @"Z(\d*\.)?\d+").Value;
string hValue = Regex.Match(s, @"H(\d*\.)?\d+").Value;
s = String.Format("G54G43{0}{1}M08", zValue, hValue);
If you have a string with serial numbers (?) in it, you may also use Regex.Replace
:
string s = "hello world Z0.5G0H5E1 this is a string";
s = Regex.Replace(s, @"(Z(?:\d*\.)?\d+)[^H]*(H(?:\d*\.)?\d+)\w*",
"G54G43$1$2M08");
That regex basically means: (Z) (number) (not H...) (H) (number) (some more letters...)
精彩评论