开发者

Convert spaces to tabs in RegEx

How do do you say the following in regex:

foreach line
   look at the beginning of the string and convert every group of 3 spaces to a tab
   Stop once a character other than a space is found

This is what i have so far:

/^ +/\t/g

However, this converts every space to 1 tab

A开发者_开发技巧ny help would be appreciated.


With Perl:

perl -pe '1 while s/\G {3}/\t/gc' input.txt >output.txt

For example, with the following input

nada
   three spaces
    four spaces
   three   in the middle
      six space

the output (TABs replaced by \t) is

$ perl -pe '1 while s/\G {3}/\t/gc' input | perl -pe 's/\t/\\t/g'
nada
\tthree spaces
\t four spaces
\tthree   in the middle
\t\tsix spaces


I know this is an old question but I thought I'd give a full regex answer that works (well it worked for me).

s/\t* {3}/\t/g

I usually use this to convert a whole document in vim do this in vim it looks like this:

:%s/\t* \{3\}/\t/g

Hope it still helps someone.


You probably want /^(?: {3})*/\t/g

edit: fixed

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜