# Match and replace very specific number

I would like to replace every number `n` in my document with `n+1`. Easy:

``````:%s/\([0-9]\+\)/\=(submatch(0)+1)/g
``````

Now I would like to replace every number `n` with `n+1`, only when the number has exactly three digits. Look behind/ahead to the rescue!

``````:%s/[0-9]\@<!\([0-9]\{3}\)[0-9]\@!/\=(submatch(0)+1)/g
``````

But now I would like to replace every number `n` with `n+1`, only when the number is between 42 and 1337. Can it be done?

Instead of moving more logic into the regular expression, move more logic into the replacement.

``````function! IncrementIf(fn, n)
if a:fn(a:n)
return n + 1
endif
return n
endfunction
:%s/\(\d\+\)/\=IncrementIf({x -> x >= 42 && x <= 1337}, submatch(0))/g
``````

You can even generalize this a bit by using partials.

``````function! If(fn, t, f, ...)
if call(a:fn, a:000)
return call(a:t, a:000)
endif
return call(a:f, a:000)
endfunction

let Inc = function('If', [{x -> x >= 42 && x <= 1337}, {x -> x + 1}, {x -> x}])

:%s/\([0-9]\+\)/\=Inc(submatch(0))/g
``````