Regex look behind in VS Code?
Update
Visual Studio Code v.1.31.0 and up have regex lookbehind support, see Wiktor's answer
Visual Studio code uses JavaScript's regular expressions as specified in ECMAScript 5, which doesn't support look behinds (https://github.com/Microsoft/vscode/issues/8635).
Here's a workaround you can try if you're doing find and replace (thanks cyborgx37):
Search Expression:
(lookbehind_expression_)text_to_replace
Replace Expression:
$1replacement_text
Given the input:
lookbehind_expression_text_to_replace
The output will be:
lookbehind_expression_replacement_text
You can use infinite-width lookahead and lookbehind
without any constraint now beginning with Visual Studio Code v.1.31.0 release.
See proof:
and another one (with (?<=@fmt\([^()]*)\w+
pattern, note the *
in the lookbehind):
See the Github [VSCode 1.31] ES2018 RegExp lookbehind assertions are now supported #68004
issue:
As a result of moving to Electron 3.0,
RegExp
lookbehind assertions are now supported, since they’re supported since Chromium 62 and Node 8.10.0, and Electron 3.0 uses Chromium 66 and Node 10.2.0, so they’re now supported, but the release notes don’t mention that lookbehind assertions are now supported.
VS Code developers confirm that it is true that they "forgot to mention it in the release notes".
Note that variable-length lookbehind assertions will only work in the file editor search, but not in the Find in Files
search (the magnifying glass icon). According to this GitHub issue discussion,
Search in the editor uses the JS regex engine, and search across files uses ripgrep which doesn't support [variable-length lookbehind assertions]. There are a small number of differences in regex feature support, this is one of them.
See these closed issues in the ripgrep
repo:
- Regexp expression failure when using lookbehind
- allow handling lookbehind assertions of non-fixed length