简体   繁体   English

C#正则表达式查找并替换

[英]C# Regex find and replace

I am trying to replace all occurrences of Secured="*" with Secured="testValue" 我正在尝试将所有出现的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() + \"\" ");

Here is my method, the issue is it changes nothing? 这是我的方法,问题是什么都不会改变?

    [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;
    }

The issue is it is not updating? 问题是它不更新吗?

You should use 你应该用

    text = r.Replace(text, "Secured=\" \"" + newValue.ToString() + "\" ");

Since the newValue is a variable. 由于newValue是一个变量。 It cannot be part of a string. 它不能是字符串的一部分。 The updated code should work: 更新的代码应该工作:

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() + "\" ");

Output: Test blah Secured="9" Test blah Secured="9" 输出: Test blah Secured="9" Test blah Secured="9"

Also, here is the function code: 另外,这是功能代码:

public string GetConvertedVdiXML(string myText, int newValue)
{
    string text = myText;
    Regex r = new Regex(@"Secured=""[^""]*"" ");
    text = r.Replace(text, "EditableBy=\"" + newValue.ToString() + "\" ");
    return text;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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