I'm trying to match a pattern only when it occurs between matching delimiters

For example, in the lines below, I'd like to match the a in the first line, but not the a in the second, which is not inside matching parens

( a )
( b ) a ( b )

The command


obviously doesn't work because it's too greedy.

I would have thought the non-greedy alternative


would work, but for some reason it returns

( A )
( b ) A ( b )

Obviously, I don't really understand how the non-greedy syntax works. Any suggestions would be most appreciated! Thanks

1 Answer 1


You could try something like that:


(\s*\(a\)\s*) can be decomposed:

  • The first pair of () are the litteral characters
  • \s* match any number of whitespace between the brackets and your pattern
  • The pair of \( and \) captures a subgroup
  • a is the subgroup captured (but you could change it to any pattern)

\U\1 is:

  • \U convert to upper case.
  • \1 the first subgroup you capted (with \( and \)).
  • Thanks, @statox, unfortunately I oversimplified the example. Your answer relied on more structure than is generally available for my case. If you could help me solve this example, maybe I could get what I need: ( a b ) ( b ) a ( b ) I want to change the first a to A but not the second. I can modify your suggestion, but it changes both expressions because in the second line, a is still between two delimiters. The difference is that in the second expression the left delimiter is matched, then the a occurs, then a new delimiter is opened
    – Leo Simon
    Sep 30, 2015 at 19:06
  • @LeoSimon: I think you should edit your question to provide some real examples so that we can see what you really want to do. Also I'm not the best with regexes so maybe someone will be able to find a better solution with an example :-)
    – statox
    Sep 30, 2015 at 22:39
  • I find it really hard to write anything complex as a comment; (the instructions on using mini-markdown formatting are too terse for me to understand) so I've posted the question, with real examples as a new thread, [link]vi.stackexchange.com/questions/4938/…\link]
    – Leo Simon
    Oct 1, 2015 at 2:44
  • @LeoSimon Okay. Actually that's what the edit button under your question is for: You can click it and modify your question to append some informations which could be useful. That's why the comments are not convenient to write complexes explications :-) If you created a new question try not to make a duplicate of this one. I'll give a look a your new question and see if I can find an answer.
    – statox
    Oct 1, 2015 at 3:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.