简体   繁体   中英

Changing a specific part of a string conditionally with Regex

This is a follow up question to a previously question I once asked:

Changing a specific part of a string

I'm using this method to change numbers inside of a string:

static string Replace(string input, int index, double addition)
{
    int matchIndex = 0;
    return Regex.Replace(
       input, @"\d+", m => matchIndex++ == index ? (int.Parse(m.Value) + addition).ToString() : m.Value);
}

I wanted to ask regarding the same scenario, what if I want to add conditions to the additions I'm doing. The addition parameter can also be a negative number and I want to throw an exception if I'm getting to a situation where I'm adding a negative number which will give a result lower than 0.

Here we go, just expand the lambda:

static string Replace(string input, int index, double addition)
{
    int matchIndex = 0;
    return Regex.Replace(input, @"\d+", m => {
        if (matchIndex++ == index) {
            var value = int.Parse(m.Value) + addition;
            if (value < 0)
                throw new InvalidOperationException("your message here");
            return value.ToString();
        }

        return m.Value;
    });
}

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