Vim Regexes匹配类,方法或函数

时间:2011-01-13 15:49:21

标签: python regex vim

我目前正在开发/更新一个VIM插件,该插件使用大量VIM Regexes来匹配 Python

中的类/方法/函数

我的出发点是重复使用我能找到的东西,在这种情况下,这就是我一直在使用的东西:

匹配一个类

    "^\\s.*class\\s\\+[a-zA-Z0-9_]\\+"
    "\ . "\\s*\\((\\([a-zA-Z0-9_,. \\t\\n]\\)*)\\)\\=\\s*:"

匹配方法

    "^\\s*.def\\s\\+[a-zA-Z0-9_]\\+\\s*(\\s*self\\_[^:#]*)\\s*:"

匹配功能

    "^\\s*def\\s\\+[a-zA-Z0-9_]\\+\\s*(\\_[^:#]*)\\s*:"

但是,上述证明了在某些情况下严格且不匹配的方式(例如,如果您启动方法并在“(”)之后继续新行。

经过多次辩论后,我决定放宽我的RegExes,这就是我目前使用的:

类别:

'\v^(.*class )'

方法:

'\v^(.*def)&(.*self)'

功能:

 '\v^(.*def )&(.*self)@!'

到目前为止一切顺利,但我认为我失去了正则表达式的平衡:现在是宽容的方式。

问题是:

  

“你可以向我宽松的正则表达式提供一些RegEx专业知识,以便它们匹配得更好但不会变得过于严格吗?”

如果你在答案中保留非常神奇的标志,

奖励积分

1 个答案:

答案 0 :(得分:4)

这样的事情可能会有所帮助,我不是蟒蛇专家,也不是VIM专家。

\v^\s*def\s+(\w+)\s*\(\s*(self[^)]*)\)\s*:

\v           # very magic
^            # start of line
   \s*       # 0 or more whitespace
   def       # 'def'
   \s+       # 1 or more whitespace
   (         # start capture group 1
      \w+       # 1 or more word [a-zA-Z0-9_] chars
   )         # end capture group 1
   \s*       # 0 or more whitespace
   \(        # '(' literal open parenthesis
   \s*       # 0 or more whitespace
   (         # start capture group 2
      self   # 'self'
      [^)]*     # 0 or more of not ')', includes newline
   )         # end capture group 2
   \)        # ')' literal close parenthesis
   \s*       # 0 or more whitespace
   :         # ':'