Fandom

Vim Tips Wiki

Search for a C-style for statement

1,624pages on
this wiki
Add New Page
Talk0 Share

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

Tip 1320 Printable Monobook Previous Next

created 2006 · complexity intermediate · author QBerrt · version 5.7


Q: How to do a search that will find both of the following examples?

for (
  int i=0;
  i<3;
  i++
)

and

for ( int i=0; i<3; i++)

A: Use this pattern

\<for\>[ ^I\n]\{-0,}([ ^I\n]\{-0,}.*;[ ^I\n]\{-0,}.*;[ ^I\n]\{-0,}.*[ ^I\n]\{-0,})

Explanation:

  • \<for\> //Match the word "for"
  • [ ^I\n]\{-0,} //Match any whitespace (space " ", tab "^I", newline "\n") 0 or more times with a non-greedy search (the negative makes it non-greedy)

Why go to all this trouble instead of searching for \<for\>?

Let's say I wanted to find all places where I do a for loop against MAX_INT. I could say:

/\<for\>[ ^I\n]\{-0,}([ ^I\n]\{-0,}.*;[ ^I\n]\{-0,}.*MAX_INT.*;[ ^I\n]\{-0,}.*[ ^I\n]\{-0,})

CommentsEdit

Another possibility using \_, which adds newline matching to various patterns:

\<for\>\_s*(\_s*.\{-};\_s*.\{-};\_s.\{-}\_s*)

May or may not satisfy your requirement exactly, but works for the given examples.


This may suffice as well for the first 2 examples:

\<for\>\_s*(\(\_s*.*;\)\{2}\_s.*\_s*)

Also on Fandom

Random Wiki