Search code examples
regexvisual-studio-codepcre

vs code can't replace using regex group references under PCRE2 mode


I'm trying to replace my std stl usage to EASTL and since i have a lot of cpp/h files, i'm relying in 'Search in Files' option of vs-code, with the following pattern:

((?<=#include \<)([^\/(.h)]+?)(?=\>))

This matches completely fine in regexr.com, in both match and replace and in vs code as well but needs the option of PCRE2 engine being enabled due backreferences use.

Trying to reference the matching group #1 using $1 under Search sidebar view simply doesn't work, and just adds "$1".

enter image description here

But if i search & replace with the same input for each file manually, it works as intended.

enter image description here

Thanks.


Solution

  • EDIT: The bug which prevented replace from working properly with lookarounds has been fixed, see capture group in regex not working. It is working in the Insider's Build and will presumably be included in v1.39.

    However, your regex:

    ((?<=#include \<)([^\/(.h)]+?)(?=\>)) should be changed to:

    ((?<=#include <)([^\/(.h)]+?)(?=>)) note the removal of escapes before < and > and then it works in the Insider's Build as of this date.

    [And the PCRE2 mode has been deprecated since the original question. So you do not need that option anymore, PCRE2 will be used automatically if needed.]


    There is a similar bug when using search/replace with newlines and the replace just literally inserts a $1 instead of the capture group's value. This bug has been fixed in the latest Insider's Build, see multiline replace issue and issue: newlines and replace with capture groups.

    But I tried your regex in the Insider's Build and it has the same result as you had before - it inserts the literal $1 instead of its value. It appears to be a similar bug but due to the regex lookarounds.

    So I tried a a simpler, but I think still correct, regex without the lookarounds:

    ^(#include\s+<)([^\.\/]+?)(>)

    and replace with $1EASTL/$2.h$3 and it works as expected.

    search replace demo: no lookarounds.