简体   繁体   中英

How to replace substrings 000-000 with new GUIDs

I need to replace all "0000-000" strings with new GUIDs. So each "0000-000" in the string should have a new GUID. So far, I've been able to replace all with one 1 new GUID. Here is a very basic code:

private string ReplaceGuids(string xmlContent)
{
    string fakeGuid = "00000000-0000-0000-0000-000000000000";
    xmlContent = @"<!--<workflow id=""00000000-0000-0000-0000-000000000000"">--><!--<workflow id=""00000000-0000-0000-0000-000000000000"">-->";

    //Method 1: replaces all 000000-00000 with the same new GUID
    xmlContent = xmlContent.Replace(fakeGuid, Guid.NewGuid().ToString().ToUpper());

    //Method 2: also replacs all 0000-00000 with the same GUID
    int pos = -1;
    do
    {
        pos = xmlContent.IndexOf(fakeGuid);
        if (pos > 0)
        {
            xmlContent = xmlContent.Replace(fakeGuid, Guid.NewGuid().ToString().ToUpper());
        }

    } while (pos > 0);

    return xmlContent;
}

I've used RegEx before but not sure how to make each 000-000 to get different new GUIDs. Thank you!

You can use the Regex.Replace method with the overload that takes a match evaluator, so that you can create a new replacement string for each match.

As you are replacing a specific string, use the Regex.Escape method to escape any characters in it that would have a special meaning as a pattern.

xmlContent = Regex.Replace(
  xmlContent,
  Regex.Escape(fakeGuid),
  m => Guid.NewGuid().ToString().ToUpper()
);

Your second method would also work if you didn't use Replace to put the GUID in the string, but use Substring to get the parts before and after the part to replace:

int pos = -1;
do {
  pos = xmlContent.IndexOf(fakeGuid);
  if (pos > 0) {
    xmlContent =
      xmlContent.Substring(0, pos) +
      Guid.NewGuid().ToString().ToUpper() +
      xmlContent.Substring(pos + fakeGuid.Length);
  }
} while (pos > 0);

Use this:

^0{8}-0{4}-0{4}-0{4}-0{12}$

or (for only "0" and "-"):

^[0-]+$

With flag MultiLine

See match demo

See replace test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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