Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

1 Answer 1

up vote 3 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
    
That's the trick. Thank you. –  Dave Jarvis Jan 15 '11 at 0:30
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.