ag Silver Searcher: rules for lookahead/lookbehind patterns?
Asked Answered
L

1

27

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?

Linearity answered 5/3, 2014 at 6:32 Comment(0)
U
32

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)'
Upstream answered 5/3, 2014 at 7:58 Comment(3)
Thank you. Using $ ag '(?<=Pragmatic )Vim' in a directory finds Vim, I am trying to find the Pragmatic part. However, since I'm trying to populate quickfix with relevant files, this command seems to limit the list to the needed files. I suppose I will need to read up on PCRE. It seems, that I will still need to use /Practical\ze for :argdo %s//Pragmatic/ge part?Linearity
Oh, sorry, I confused that. It's now corrected. Thanks for accepting my answer!Upstream
You're correct that the PCRE syntax only applies to the external ag command. For :s inside Vim, you still have to use \ze.Upstream

© 2022 - 2024 — McMap. All rights reserved.