简体   繁体   English

如何在vim命令中使用正则表达式格式化电话号码列表?

[英]How do I format a list of phone numbers using regular expression in vim commands?

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 写一个正则表达式(在loki上使用vim)重新格式化数字,使它们看起来像这样

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? 有任何想法吗?

尝试这个:

:%s,.*\(\d\d\d\).*\(\d\d\d\).*\(\d\d\d\d\).*,\1 \2 \3,

First use count to match a pattern multiple times, it is a bad habbit to repeat the pattern: 第一次使用count来多次匹配一个模式,重复该模式是个坏习惯:

\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 : 甚至更好的是,使用\\v转义整个正则表达式:

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

This greatly increases readability 这大大提高了可读性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM