Home > Enterprise >  how to Replace a dynamic value
how to Replace a dynamic value

Time:12-10

this is my text file and I want replace "TP661" But this number changes every time

"algo": null,
"coin": null,
"url": "Domain",
"user": "UserWord",
"pass": "TP661",
"rig-id": null,
"nicehash": false,
"keepalive": true,
"enabled": true,
"tls": true,
"tls-fingerprint": null,
"daemon": false,
"socks5": null,
"self-select": null,
"submit-to-origin": false

this is my code I was trying to change the whole line It is possible that there is another letter instead of TP661 or number

private void btn_replace_Click(object sender, EventArgs e)
{
    string[] lines = richTextBox1.Text.Split('\n');
    string split = "pass";
    var sb = new StringBuilder();
    foreach (var item in lines)
    {
        sb.AppendLine(item);
        //foreach (var item2 in split)
        {
            if (item.Contains(split))
            {
                sb.Replace(split, txt_replace.Text);
            }
        }
    }
    richTextBox1.Text = sb.ToString();
}

CodePudding user response:

You can use a regular expression to find and replace that specific line in the text. If you want to be able change also other lines, another approach may be better.

private void btn_replace_Click(object sender, EventArgs e)
{
    // Regular expression pattern 
    const string pattern = @"\""pass\"": \"".*?\"",";
    
    // get text from text box
    string text = richTextBox1.Text;
    
    // Build replacement for line 
    string replacement = @"""pass"": """   txt_replace.Text   @""",";
    
    // Replace pattern with replacement
    text = Regex.Replace(text, pattern, replacement);
    
    // Put result into Text Box
    richTextBox1.Text = text;
}
  • Related