在RegEx中将空格转换为制表符

时间:2009-12-06 02:29:50

标签: regex string

你怎么说正则表达式中的以下内容:

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

这是我到目前为止所做的:

/^ +/\t/g

但是,这会将每个空格转换为1个标签

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:7)

使用Perl:

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

例如,使用以下输入

nada
   three spaces
    four spaces
   three   in the middle
      six space

输出(TAB替换为\t)是

$ 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

答案 1 :(得分:3)

我知道这是一个老问题,但我认为我会给出一个完整的正则表达式的答案(这对我有用)。

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

我通常使用它在vim中转换整个文档在vim中这样做:

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

希望它仍能帮到某人。

答案 2 :(得分:-1)

您可能需要/^(?: {3})*/\t/g

编辑:修复