search

Home  >  Q&A  >  body text

Regular expression - how to match square bracket pairs in vim

It seems that I use \[ to match [, use ] to match]. I use \[*] to match the square bracket pair, but a\[*] cannot match the bracket pair with a in front (array a) , but using a\[ can match a and the left bracket after a. Why?

phpcn_u1582phpcn_u15822742 days ago938

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-05-16 16:43:46

    \[*]匹配的是0到多个[,后面是一个],例如],[],[[]等
    中间的*匹配的[,并不是指中括号中间的任意字符重复0-N次。
    
    中括号中间的任意字符,简单的话可以使用.*表示,但是同一行有多个中括号的话会全部匹配,如:
    a[i+1]= b[i-1]这样的表达式会被全部匹配。
    
    试一下下面这个,应该可以匹配a后面的带中括号的表达式
    a\[[^]]*]   
    

    reply
    0
  • 黄舟

    黄舟2017-05-16 16:43:46

    My test result is a[*] 可以匹配到 a[]。当然它不能匹配 a[i].

    But are you sure you want to use *? Your "like" makes me have the urge to give you a tutorial on regular expressions...

    [...] 是用来匹配字符类的,比如 [abd] 匹配 a, b 或者 d 中的任何一个。因为 [] 已经有这个意思了,所以要匹配到 [ 字符需要转义 [,要匹配 ] 的话原则上也是要转义的 ], but it does not need to be escaped when it does not cause ambiguity.

    * 是一个量词,它表示前边那个字符(或者字符类字符组 is a quantifier, which means that the previous character (or character class, character group) can appear anywhere Multiple times (0 times also counts).

    reply
    0
  • Cancelreply