Pete
Pete

Reputation: 3

C# Regex find and replace

I am trying to replace all occurrences of Secured="*" with 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?

Upvotes: 0

Views: 459

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627370

You should use

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

Since the newValue is a variable. 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"

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

Upvotes: 1

Related Questions