如何避免第二次对齐受第一次对齐的影响?

时间:2013-06-19 12:41:10

标签: regex vim alignment tabular

我的文字示例:

this is my text,this is,this is my text
this, this is my,this is my,this is text

我使用Tabular插件来对齐文字。

当我想在单个空格'\s'的第1和第2次出现时对齐时,我使用这些行:

Tabularize /^\(.\{-}\zs\s\)\{1}/l0
Tabularize /^\(.\{-}\zs\s\)\{2}/l0

但是我注意到第一个对齐添加了空格以便对齐, 但是第二次对齐会受到这些额外空间的影响,而且不是正确的工作。

我该如何避免这种情况? (我希望自己明确表示)

修改:

这就是我的预期:

this  is   my text,this is,this is my aatext
this, this is my,this is my,this is rtext

这是结果:

this       is my text,this is,this is my aatext
this, this is my,this is my,this is rtext

EDIT2:

这是我的例子,> = 2个空格:

this  is my  text, this is,this  is my aatext
this,  this    is my, this is my,  this is rtext

在下面的答案中修改Nikita Kouevda提出的代码:

Tabularize /\(^\(\(\S*\s\{2,}\)\{0}\|\(\S*\s\{2,}\)\{2}\)\)\@<=\S*\zs\s/l0

我期待:

this  is my  text, this is,this  is my aatext
this, this    is my, this is my, this is rtext

结果:

this  is my  text, this is,this  is my aatext
this, this                                     is my, this is my,  this is rtext

1 个答案:

答案 0 :(得分:1)

我不熟悉Tabular,可能有选项可以执行此操作,但我只需将第二个\s更改为\s\+即可匹配任意数量的空白:

Tabularize /^\(.\{-}\zs\s\+\)\{2}/l0

编辑:这是一个更合适的解决方案,将这些步骤合并为一个:

Tabularize /\(^\(\S*\s\)\{,1}\)\@<=\S*\zs\s/l0

第一部分是与第0或第1空格匹配的lookbehind,然后跳过任何非空白字符,并匹配下一个空格(分别为第1和第2个空格)。这可以推广到任何范围;例如要按第2到第5个空格对齐,请使用\{1,4}

编辑:如果您需要通过一组不构成范围的空格来对齐,我会在后视中使用逻辑OR。不幸的是,这变得更加笨拙和重复。例如,要按第1和第3个空格对齐:

Tabularize /\(^\(\(\S*\s\)\{0}\|\(\S*\s\)\{2}\)\)\@<=\S*\zs\s/l0

为了区别对齐每个列,请指定多种[lcr]#格式。请注意,每个分离和分离的列都要计算在内;例如通过2个空格对齐将产生5个将被格式化的列。为了通过第1和第3个空格对齐,并右对齐文本的中间列:

Tabularize /\(^\(\(\S*\s\)\{0}\|\(\S*\s\)\{2}\)\)\@<=\S*\zs\s/l0l0r0l0l0

由于格式循环如果你指定的列数少于列数,l0l0r0在这里也足够了,但明白这可能是一个好主意。