使用Regex有条件地更改字符串的特定部分

时间:2014-06-28 12:52:14

标签: c# regex

这是我曾经问过的先前问题的后续问题:

Changing a specific part 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);
}

我想询问相同的情况,如果我想为我正在做的补充添加条件该怎么办? addition参数也可以是负数,如果我遇到的情况是我添加一个负数会得到低于0的结果,我想抛出异常。 / p>

1 个答案:

答案 0 :(得分: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;
    });
}