3

I need to put a comma between any two digits in a string of digits. For example, I want this

12345678910

to become this

1,2,3,4,5,6,7,8,9,1,0

The approach I took was the following

s/\([0-9]\)\([0-9]\)/\1,\2/g

Strangely enough, the substitution command above when applied to the string in the example gives

1,23,45,67,89,10

If I apply the substitution command once again, it gives what I want. But why just one instance of the command don't work?

The vim version I'm using is

VIM - Vi IMproved 8.0 (2016 Sep 12, compiled Mar 18 2020 18:29:15)
7

why just one instance of the command don't work?

Obviously, the string is parsed as (12)(34)(56)(78)(91)0 --> 1,2 3,4 5,6 7,8 9,1 0

A possible solution is s/\d\d\@=/\0,/g. See :h /\@=.

| improve this answer | |
  • This \@= thing is very nifty. Didn't know of it, though. Thanks! – Larara Sep 1 at 5:50
  • Or s/\d\ze./&,/g. A little shorter, maybe a little more efficient (not that one would notice with such small inputs). On the con side, you want to make sure there are only numbers (otherwise s/\d\ze\d/&,/g). – B Layer Sep 24 at 7:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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