Alex Rivera | Logout

Match parenthesised block using regular expressions in vim

Asked 2011-02-28T07:37:24.803
10

I'm trying to match the contents that belong between a certain ( and its matching ) as found by vim when using the motion %.

More specifically, I'm looking for a regex that looks like this hypothetical /someKeyword (\{pair}\(.*\))\{pair}/, if there were such modifiers as \{pair} that when applied to two exactly two characters in a regex, makes the second one only match if it's the matching bracket to the first one (%-wise).

The pattern I'm looking for should match the inner contents of the first bracket following someKeyword (n.b. the code that it should work on is always correctly bracketed), as in the examples:

For someKeyword ("aaa") the submatch will match "aaa". Likewise someKeyword ("aaa)") will match "aaa)" and someKeyword(("double-nested stuff")) will match ("double-nested stuff")

But also in cases like:

(
  someKeyword("xyz"))

where it should match "xyz".

Is there any way to make use of vim's matching bracket functionality in regexes? And if not, what other solution might work to accomplish this?

Edit 1: the matched contents may span several lines.

Edit
Report

2 Answers

1

As Jens told, this cannot be done with Vim regular expressions.

However if you want to do some special processing you can possibly do the following:

  • Find opening parentheses that interest you and then run a macro that will insert some character (let's say ^@) after the opening parenthese and before the closing parenthese using the % binding.
  • Then modify the regex accordingly.
answered 2011-02-28T07:54:30.060
1

You could do this quite easily with a macro. You would search for the keyword with a regexp and then search for the start of the text, then the end of it, then you can undertake what ever action that you want.

E.g. to yank the required text:

qa/somekeyword\s*
/(
lvh%hyq

Now whenever you use the macro with @a you would yank the next bit of text that you are interested in.

answered 2011-02-28T08:08:20.367

Your Answer