Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ag Silver Searcher: rules for lookahead/lookbehind patterns?

Tags:

regex

vim

vimgrep

I'm using ag in Vim with good results for string/file search.

However, there seems to be not much documentation how patterns are constructed for ag.

I'm trying to use ag instead of vimgrep in an example from the Practical Vim book.

I want to find every occurrence of "Pragmatic Vim" in all files in a directory recursively, and substitute this string with "Practical Vim". There is also "Pragmatic Bookshelf" in some files, and that string must remain.

the book suggests this approach:

/Pragmatic\ze Vim :vimgrep /<C-r>// **/*.txt 

And after that step, populate quickfix list with :Qargs plugin command, and, finally :argdo %s//Practical/g

Now, how do I specify /Pragmatic\zepattern using ag?

Is ag at all designed for what I'm trying to do here?

like image 767
user3156459 Avatar asked Mar 05 '14 06:03

user3156459


People also ask

What is lookahead and Lookbehind in regex?

Lookahead allows to add a condition for “what follows”. Lookbehind is similar, but it looks behind. That is, it allows to match a pattern only if there's something before it.

Can I use regex lookahead?

Lookahead assertions are part of JavaScript's original regular expression support and are thus supported in all browsers.

What does lookahead do regex?

Lookahead is used as an assertion in Python regular expressions to determine success or failure whether the pattern is ahead i.e to the right of the parser's current position. They don't match anything. Hence, they are called as zero-width assertions.

What is Lookbehind?

Lookbehind has the same effect, but works backwards. It tells the regex engine to temporarily step backwards in the string, to check if the text inside the lookbehind can be matched there. (? <!a)b matches a “b” that is not preceded by an “a”, using negative lookbehind.


1 Answers

The Silver Searcher tool uses PCRE (Perl-Compatible Regular Expression) syntax. So instead of Vim's \ze, you need to use the Perl syntax for positive lookahead: (?=pattern). (The corresponding lookbehind for \zs would be (?<=pattern).)

I'm showing your example on the command-line, but it should be identical from within Vim:

$ ag 'Pragmatic(?= Vim)' 
like image 96
Ingo Karkat Avatar answered Nov 03 '22 02:11

Ingo Karkat