Regex in Visual Studio Code: Invalidate match fail

2020-01-29 02:36发布

问题:

Edit: As several commenters have pointed out, it should be ^class (?!Migration)[A-Z][a-z]*. But VS Code complains: Error parsing regex near "ss (?!Migr' at character offset 9: Unrecognized flag: '!'. (Allowed flags: i, m, s, U, u, x.)

Visual Studio seems to support negative look aheads (see "Invalidate a match") . Could not find an answer to the question if VSCode does support it.


In VS Code I am trying to find class definitions in a Django project via Shift+Command+F. Turned on regex search. Now my search pattern is this:

^class [A-Z][a-z]*

So every occurence of "class Abc", where Abc is the class name, will be found.

Now I would like to exclude classes like class Migration(...) or class Command(...)

I tried to do this with a negative lookahead, like so:

^class (!?Migration)[A-Z][a-z]*

But that won't work. VS Code will show me all classes named class Migration(...), so instead of excluding it, it will focus on it.

What am I missing?

回答1:

Note that to make your patterns with lookaheads work you need to edit your settings.json file to set

"search.usePCRE2": true

See the v1.29 release notes:

It is also now possible to use backreferences and lookahead assertions in regex searches, by setting "search.usePCRE2": true. This configures ripgrep to use the PCRE2 regex engine. While PCRE2 supports many other features, we only support regex expressions that are still valid in JavaScript, because open editors are still searched using the editor's JavaScript-based search.

Also, see Mark's answer who noticed this option earlier.

Then, your ^class (?!Migration)[A-Z][a-z]* regex will work.



回答2:

Use a visual studio code extension called Reverse Search for this purpose