Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Background

Add a constant value to numbers matched with a regular expression, using vim (gvim).

Problem

The following regular expression will match width="32":

/width="\([0-9]\{2\}\)"

Question

How do you replace the numeric value of the width attribute with the results from a mathematical expression that uses the attribute's value? For example, I would like to perform the following global replacement:

:%s/width="\([0-9]\{2\}\)"/width="\1+10"/g

That would produce width="42" for width="32" and width="105" for width="95".

Thank you!

share|improve this question
up vote 4 down vote accepted

To do expression evaluation in the substitution, see:

:help :s\=
:help submatch()

For example:

:%s/width="\([0-9]\{2\}\)"/\='width="'.(submatch(1)+10).'"'/g

When you do expression substitution the entire substitution must be an expression, so you have to concatenate (see :help expr-.) the three elements of the expression. Broken down:

  • \=

Indicate the replacement pattern is an expression.

  • 'width="'

The first string.

  • (submatch(1) + 10)

Add ten to the first sub-pattern-match—enclosed in parenthesis so Vim doesn't try to include the preceding string in the addition operation.

  • '"'

The closing quote as a string.

(Note that I did not include the concatenation operators in the breakdown.)

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .