tags:

views:

122

answers:

4

I have a sequence of digits like below. I want to combine digits to group of 4. Can someone give a vim regex to do that?

Input : 1234 56 7890 1234

The output should be: 1234 5678 9012 34

+10  A: 

Two pass:

s/ //g
s/\(.\{4\}\)/\1 /g
Autocracy
I was just wondering, if there exist a regex that can do in one pass
chappar
I don't think there is a way to so this in one pass with a regex. I can't think of how to remove the spaces in the same pass as grouping into 4s.
Autocracy
@Autocracy - You CAN do it in one pass, but it's awful. I +1'ed because this is the best solution in my opinion, but for a one-pass solution, see my answer: http://stackoverflow.com/questions/910133/regex-for-combining-digits/910222#910222
Chris Lutz
Hmmmm... interesting, CPU consuming, and brain damaging :)Congrats on coming up with that. Almost an antipattern.
Autocracy
"Almost" an antipattern?
Chris Lutz
+4  A: 

I would do this in two steps: (1) remove the blanks right of digit groups

:s/\(\d\+\) /\1/g

(2) grouping:

:s/\(\d\{4}\)/\1 /g

In case of many lines record a macro
or do these steps for an marked area.

fgm
+4  A: 

You can do it in one pass, but it looks awful:

:s/\(\d\) *\(\d\) *\(\d\) *\(\d\) */\1\2\3\4 /g

While this works, it's rather asinine. It's faster to do one of those nice two-pass solutions than to spend 2 minutes working out one Monsteregex™ that does it in one pass. Plus, the two-pass solutions are easier to understand.

Chris Lutz
+1  A: 
:s/\(\d\)\s*\(\d\)\s*\(\d\)\s*\(\d\)\s*/\1\2\3\4 /g

works, but I prefers Autocracy's solution.

Luc Hermitte