Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VSCode Vim Search and Replace capture group

Edit: I just tried this in the VSVim extension in VS2019, and it worked as expected. I'm starting to think that VSCodeVim extension for VSCode doesn't handle captures properly?

I am trying to search my typescript file for a list of variables that have not yet been assigned an initial value, and set it to = null.

  private __requestor: Req;
  private __feedback: FeedbackObject;
  private __dueDate: Calendar = null;
  private __priority: number = NaN;
  private __bigTest = TestObject;

I am using the following command: :%s/(: [a-zA-Z]+);/\1 = null;/g

I expect the output to stick = null on lines 1, 2 and 5, but instead it sticks a \1.

Expected:

  private __requestor: Req = null;
  private __feedback: FeedbackObject = null;
  private __dueDate: Calendar = null;
  private __priority: number = NaN;
  private __bigTest: TestObject = null;

Actual:

  private __requestor\1 = null;
  private __feedback\1 = null;
  private __dueDate: Calendar = null;
  private __priority: number = NaN;
  private __bigTest\1 = null;

Is there something wrong with my regex/search & replace command? It looks similar to the other S&R commands that use capture groups in examples I've seen, and I haven't seen any settings for "enabling" capture groups.

like image 920
Acorn Avatar asked Mar 05 '26 11:03

Acorn


2 Answers

Apparently in VSCodeVim, capture groups are recognized with $1, $2, etc.. rather than \1, \2, etc...

So, using this worked:

:%s/(: [a-zA-Z]+);/$1 = null;/g

Source: https://github.com/VSCodeVim/Vim/issues/4502

like image 87
Acorn Avatar answered Mar 08 '26 03:03

Acorn


Using more regex groups:

:%s/\v(__\w+)(:| \=) ([A-Z][a-zA-Z]+);/\1: \3 = null; 

 % ....................... whole file
 \v ...................... very magic (avoid some scapes)
 (__\w+)  ................ first group (matches __word)
 (:| \=)  ................ second group, followed by : or space plus =
 ([A-Z][a-zA-Z]+) ........ third group (matches CamelCaseWords) 
 ; ....................... followed by literal ;

OBS: What makes difficult to reach a proper result is the fact that line 5 has a different pattern.

like image 25
SergioAraujo Avatar answered Mar 08 '26 03:03

SergioAraujo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!