【问题标题】:How to match against only first = in Vim using Tabular, ignoring ==, <=, >=, !=, /=, etc?如何使用表格在 Vim 中仅匹配第一个 =,忽略 ==、<=、>=、!=、/= 等?
【发布时间】:2014-04-14 22:53:17
【问题描述】:

我正在尝试使用 Tablular 匹配一行中的第一个赋值运算符,忽略该行中包含 = 的其他运算符(例如 ==&lt;=&gt;=/=!=~=等)

到目前为止,我得到的最好的结果如下:

:Tabularize /\zs[=<>/!]\@<!=[=<>/!]\@!\ze/<CR>

它的作用是匹配=,确保它的任一侧都不是=&lt;&gt;/!

如果我在一行中只有一个作业,则此方法有效,例如:

one = uno
two = dos
three = tres

变成

one   = uno
two   = dos
three = tres

但是,如果我在一行中有多个作业,例如:

one = uno = alpha
two = dos = beta
three = tres = gamma

然后我最终得到(注意对齐的第二组等号):

one   = uno  = alpha
two   = dos  = beta
three = tres = gamma

我真正想要的只是(注意第二组等号未对齐):

one   = uno = alpha
two   = dos = beta
three = tres = gamma

我真正想要的是让 Tablular 仅匹配上面的第一个赋值运算符,注意不要匹配其中也包含 = 的其他运算符。

我必须对模式/\zs[=&lt;&gt;/!]\@&lt;!=[=&lt;&gt;/!]\@!\ze/ 做什么才能实现这一点?

【问题讨论】:

    标签: regex vim variable-assignment tabular


    【解决方案1】:

    我认为您只需在正则表达式的末尾添加一个.*(而不是\ze

    :Tabularize /\zs[=<>/!]\@<!=[=<>/!]\@!.*/
    

    仅包含该行的其余部分作为分隔符的一部分。

    【讨论】:

      【解决方案2】:

      有一些常用的:Tabular 成语派上用场:

      • 使用\zs 在模式中的某个点开始匹配
      • .* 结束模式以消耗该行的其余部分以防止更多匹配

      我赞成使用消极的前瞻和后瞻,但我认为我们可以让它更简单一点:

      :Tabularize/\s\zs=\s.*/
      

      这假设您的运算符两侧都有一个空格(假设您的代码格式很好)

      如需更多帮助,请参阅:

      :h /\zs
      :h tabular-walkthrough
      

      【讨论】:

        【解决方案3】:

        :help tabular的“演练”部分有一个例子:

        But, what if you only wanted to act on the first comma on the line, rather than
        all of the commas on the line?  Let's say we want everything before the first
        comma right aligned, then the comma, then everything after the comma left
        aligned:
        
            abc,def,ghi
            a,b
            a,b,c
        
            :Tabularize /^[^,]*\zs,/r0c0l0
        
            abc,def,ghi
              a,b
              a,b,c
        
        Here, we used a Vim regex that would only match the first comma on the line.
        It matches the beginning of the line, followed by all the non-comma characters
        up to the first comma, and then forgets about what it matched so far and
        pretends that the match starts exactly at the comma.
        

        您可以轻松适应您的需求:

        :Tabularize /^[^=]*\zs=
        

        【讨论】:

        • 我认为这不像告诉正则表达式与前面的 = 符号不匹配那么简单。这就是为什么我强调我想忽略前面可能包含 = 的运算符这一事实。
        • 我的回答解决了您在问题中描述的问题:仅对齐行中的第一个 =。请注意,当您正在对齐的块中的某处有 -=+= 时,接受的答案会中断,并付出更多努力才能得到与我的命令完全相同(不满意)的结果。
        猜你喜欢
        • 1970-01-01
        • 2020-06-16
        • 2015-10-22
        • 1970-01-01
        • 2011-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多