Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert spaces to tabs in RegEx

Tags:

string

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

Any help would be appreciated.

like image 419
simonwjackson Avatar asked Dec 06 '09 02:12

simonwjackson


People also ask

What is the regex for tab?

Use \t to match a tab character (ASCII 0x09), \r for carriage return (0x0D) and \n for line feed (0x0A).

How do you match a space in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

How do you replace spaces with tabs in Notepad ++?

To convert existing tabs to spaces, press Edit->Blank Operations->TAB to Space . If in the future you want to enter spaces instead of tab when you press tab key: Go to Settings->Preferences...


2 Answers

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
like image 175
Greg Bacon Avatar answered Sep 28 '22 17:09

Greg Bacon


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.

like image 29
xaocon Avatar answered Sep 28 '22 15:09

xaocon