使用正则表达式有条件地更改字符串的特定部分

本文关键字:字符串 定部 正则表达式 有条件 | 更新日期: 2023-09-27 18:10:35

这是我之前问过的一个问题的后续问题:

修改字符串的特定部分

我用这个方法来改变字符串里面的数字:

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

我想问关于同样的场景,如果我想在我正在做的添加中添加条件该怎么办?addition参数也可以是一个负数,我想抛出一个异常,如果我得到的情况下,我正在添加一个负数,这将给出一个结果低于0。

使用正则表达式有条件地更改字符串的特定部分

现在展开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;
    });
}