简体   繁体   中英

How would I remove a certain amount of text after a string?

So, let's say there is:

MinimumPasswordAge = 4

I want to replace the 4, except the 4 will be a random number.

Or, how can i remove 1-2 characters after

MinimimPasswordAge =

BTW, this is all in a text file.

There are many many ways to do this. However, here is a regex example

var input = "MinimumPasswordAge = 4";
var result = Regex.Replace(input, @"(?<=MinimumPasswordAge = )\d+", "345");
Console.WriteLine(result);

Output

NumValue = 345

Full Demo Here

Note :This is assuming you know how to read all the text from the text file, and subsiquently write to one using Eg File.ReadAllText / File.ReadLines methods

Updated from Eric J 's worthy comment

Use this pattern for white space tolerance

(?<=MinimumPasswordAge\s?=\s?)\d+

If you'd like a non-RegEx version, try basic string parsing:

    public static string ReplaceValue(string str, object value)
    {
        var eq = str?.IndexOf('=');
        if(eq.GetValueOrDefault(-1) != -1)
        {
            return $"{str.Substring(0, eq.Value + 1)}{value}";
        }
        return str;
    }

Then call it like this:

    var myKeyValue = "HelloWord=123";
    myKeyValue = ReplaceValue(myKeyValue, 456);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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