C# 正则表达式查找和替换
C# Regex find and replace
我正在尝试将所有出现的 Secured="*" 替换为 Secured="testValue"
int testValue = 9;
string text = "Test blah Secured=\"6\" Test blah Secured=\"3\" ";
Regex r = new Regex("Secured=\".*\" ");
text = r.Replace(text, "Secured=\" \" + newValue.toString() + \"\" ");
这是我的方法,问题是它没有任何变化吗?
[Published]
public string GetConvertedVdiXML(string myText, int newValue)
{
string text = myText;
Regex r = new Regex("Secured=\".*\" ");
text = r.Replace(text, "Secured=\" " + newValue.ToString() + " \" ");
return text;
}
问题是它没有更新?
你应该使用
text = r.Replace(text, "Secured=\" \"" + newValue.ToString() + "\" ");
因为newValue
是一个变量。它不能是字符串的一部分。更新后的代码应该可以工作:
int newValue = 9;
string text = "Test blah Secured=\"6\" Test blah Secured=\"3\" ";
Regex r = new Regex(@"Secured=""[^""]*"" ");
text = r.Replace(text, "Secured=\"" + newValue.ToString() + "\" ");
输出:Test blah Secured="9" Test blah Secured="9"
另外,这里是函数代码:
public string GetConvertedVdiXML(string myText, int newValue)
{
string text = myText;
Regex r = new Regex(@"Secured=""[^""]*"" ");
text = r.Replace(text, "EditableBy=\"" + newValue.ToString() + "\" ");
return text;
}
我正在尝试将所有出现的 Secured="*" 替换为 Secured="testValue"
int testValue = 9;
string text = "Test blah Secured=\"6\" Test blah Secured=\"3\" ";
Regex r = new Regex("Secured=\".*\" ");
text = r.Replace(text, "Secured=\" \" + newValue.toString() + \"\" ");
这是我的方法,问题是它没有任何变化吗?
[Published]
public string GetConvertedVdiXML(string myText, int newValue)
{
string text = myText;
Regex r = new Regex("Secured=\".*\" ");
text = r.Replace(text, "Secured=\" " + newValue.ToString() + " \" ");
return text;
}
问题是它没有更新?
你应该使用
text = r.Replace(text, "Secured=\" \"" + newValue.ToString() + "\" ");
因为newValue
是一个变量。它不能是字符串的一部分。更新后的代码应该可以工作:
int newValue = 9;
string text = "Test blah Secured=\"6\" Test blah Secured=\"3\" ";
Regex r = new Regex(@"Secured=""[^""]*"" ");
text = r.Replace(text, "Secured=\"" + newValue.ToString() + "\" ");
输出:Test blah Secured="9" Test blah Secured="9"
另外,这里是函数代码:
public string GetConvertedVdiXML(string myText, int newValue)
{
string text = myText;
Regex r = new Regex(@"Secured=""[^""]*"" ");
text = r.Replace(text, "EditableBy=\"" + newValue.ToString() + "\" ");
return text;
}