How would I formulate a search pattern for matching if statements that don't have an opening curly brace on the next line? I assume it requires the use of something like [^{] or \@!, but I'm having trouble getting things to work correctly.

I'd like to match:


but not:


The if and { may be indented one or more levels and I think trying to account for the indentation is what's causing my problems.

My first attempt was to use this pattern:


This works if things aren't indented, but once they are it matches any if statement regardless of whether the first non-white space character on the next line is a {.

  • Of course: When indended, the last whitespace before the { will be matched by the [^{], while the \s* eats one whitespace less. To avoid this, include the whitespace (and TAB, if needed) in that exclusion list: [^ {] – Philippos Sep 8 '17 at 13:16

Of course just before clicking the submit button, I thought of a way to do it:


This works by capturing any white space before the if and searching for the same amount of white space at the start of the next line (using \1). Note that this assumes that the white space before the { exactly matches the white space before the if.

The \zs and \ze just limit the highlighting to the actual if line.

  • In case you ever try to do this in a different regex language. You are looking lookaround assertions. More than likely a negative lookahead assertion. Many language do not provide \zs and \ze style zero-width assertions. Perl does have a zero-width assertion, \K, which is similar to Vim's \ze. – Peter Rincker Sep 8 '17 at 0:05
  • This will fail for either wrong indentions or mixed tab/whitespace indentions. – Philippos Sep 8 '17 at 13:18
  • That's a good point. I will clarify that my solution makes a number of assumptions. Fortunately, they are assumptions that are valid for the code I'm currently dealing with. – Pak Sep 8 '17 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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