sumowrestler
sumowrestler

Reputation: 365

How to add quotations around numbers in Vim - Regex?

I have been trying, unsuccessfully, to add quotation marks around some numbers in my file using regex. To clarify, let me give an example of what I am trying to do.

Something like myFunction(100) would be changed to myFunction("100").

I thought :100,300s/\([0-9]*\)/"\0" would work but it put quotation marks around spaces as well.

What can I do to fix this?

Upvotes: 3

Views: 840

Answers (2)

Will Durney
Will Durney

Reputation: 1208

The reason this isn't working as expected is because [0-9]* is matching all strings of zero length, so your substitution is adding two quotes between every two characters. Changing it to [0-9]+ (to require at least one digit) will solve your problem.

As an additional improvement, you can replace [0-9] with \d. Also, \0 is the replacement for the entire matched expression, so your parentheses are unnecessary: :100,300s/\d+/"\0" will accomplish what you want. Captured subgroups start at \1.

Upvotes: 1

ntalbs
ntalbs

Reputation: 29438

You should slightly modify the regular expression:

%s/\(\d\+\)/"\1"

In regular expression, first matched group is \1, not \0. And it looks safer to use \+ instead of *.

Upvotes: 2

Related Questions