[英]How do I convert a masked textbox to an int with the mask of 000-000?
[英]How to replace substrings 000-000 with new GUIDs
我需要用新的GUID替换所有的“ 0000-000”字符串。 因此,字符串中的每个“ 0000-000”都应具有一个新的GUID。 到目前为止,我已经能够用一个1个新的GUID替换全部。 这是一个非常基本的代码:
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;
}
我以前使用过RegEx,但不确定如何使每个000-000来获得不同的新GUID。 谢谢!
您可以将Regex.Replace
方法与带有比赛评估器的重载一起使用,以便可以为每个比赛创建一个新的替换字符串。
当您替换特定的字符串时,请使用Regex.Escape
方法对其中具有特殊含义的所有字符进行转义,以作为模式。
xmlContent = Regex.Replace(
xmlContent,
Regex.Escape(fakeGuid),
m => Guid.NewGuid().ToString().ToUpper()
);
如果您不使用Replace
将GUID放入字符串中,而是使用Substring
来获取要替换的部分之前和之后的部分,则第二种方法也将起作用:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.