1

Given the following list of phone numbers

8144658695
812 673 5748
812 453 6783
812-348-7584
(617) 536 6584
834-674-8595

Write a single regular expression (use vim on loki) to reformat the numbers so they look like this

814 465 8695
812 673 5748
812 453 6783
812 348 7584
617 536 6584
834 674 8595

I am using the search and replace command. My regular expression using back referencing:

:%s/\(\d\d\d\)\(\d\d\d\)\(\d\d\d\d\)/\1 \2 \3\g 

only formats the first line. Any ideas?

markalex
  • 8,623
  • 2
  • 7
  • 32
aschenk04
  • 21
  • 3

2 Answers2

1

Try this:

:%s,.*\(\d\d\d\).*\(\d\d\d\).*\(\d\d\d\d\).*,\1 \2 \3,
ffledgling
  • 11,502
  • 8
  • 47
  • 69
1

First use count to match a pattern multiple times, it is a bad habbit to repeat the pattern:

\d\{3} "instead of \d\d\d

Than you also have to match the whitespaces etc:

:%s/.*\(\d\{3}\).*\(\d\{3}\).*\(\d\{4}\).*/\1 \2 \3/g 

Or even better, escape the whole regex with \v:

:%s/\v.*(\d{3}).*(\d{3}).*(\d{4}).*/\1 \2 \3/g

This greatly increases readability

Doktor OSwaldo
  • 5,732
  • 20
  • 41
  • I tried this originally and it didn't work. Forgot I had to escape the `{` and `}` as well! Damn regex dialects. – ffledgling Feb 22 '17 at 18:31
  • huh why the downvote ? and yeah it is a bit cumbersome but you could use the \v trick to not escape, see my updated answer @ffledgling – Doktor OSwaldo Feb 23 '17 at 07:09
  • I'm not the one that downvoted, I'm sorry if my comment comes across as criticism, I actually meant it as something I should've done, but didn't. Upvoting for the `\v` trick which I didn't know about. – ffledgling Feb 23 '17 at 12:38
  • @ffledgling Sorry, i didn't meant you with the downvote, hasn't understood it as criticism. But thank you for the upvote, and i wish you a nice day! – Doktor OSwaldo Feb 23 '17 at 12:54