Home > Back-end >  VS Code Regex search: find a term inside loop/function/etc?
VS Code Regex search: find a term inside loop/function/etc?

Time:10-12

Using VS Code's Search panel, let's say I want to find foo only if it's in a while loop. So in the example below, I'd only want to find foo = baz. How would I go about composing this search term?

const numbers = [1, 2, 3];

numbers.forEach((number) => {
    foo = 'bar';
});

let count = 0;
while (count < numbers.length) {
  count  ;
  foo = 'baz';
}

for (let i = 0; i < numbers.length; i  ) {
  foo = 'qux';
}

I've attempted a few different regexes, but the closest I've gotten is while.*\n*.*foo, which will find it only if it's on the very next line. With count there, it doesn't find it.

CodePudding user response:

First, I want to say that I don't think regex is the best tool to parse language syntax. This is a complicated matter. In this specific case you may be able to use the below, but if something in your file is a bit different, you could end up having to tweak it again.

You can use non-capturing group with a negative lookahead inside, making it stop at the next foo, so the first match won't include the rest of the file, basically. Then you can use a capturing group to capture everything until foo, so that you will be able to only replace foo.

Search: (while(?:(?!foo).|\n)*)foo
Replace: $1bar

https://regex101.com/r/lW4TlF/1

It will make this

const numbers = [1, 2, 3];

while (count < numbers.length) {
  count  ;
  foo = 'baz';
}

numbers.forEach((number) => {
    foo = 'bar';
});

let count = 0;
while (count < numbers.length) {
  count  ;
  foo = 'baz';
}

for (let i = 0; i < numbers.length; i  ) {
  foo = 'qux';
}

while (count < numbers.length) {foo = 'baz';  count  ;}

while (count < numbers.length) {
  foo = 'baz';  count  ;
}

Into this

const numbers = [1, 2, 3];

while (count < numbers.length) {
  count  ;
  bar = 'baz';
}

numbers.forEach((number) => {
    foo = 'bar';
});

let count = 0;
while (count < numbers.length) {
  count  ;
  bar = 'baz';
}

for (let i = 0; i < numbers.length; i  ) {
  foo = 'qux';
}

while (count < numbers.length) {bar = 'baz';  count  ;}

while (count < numbers.length) {
  bar = 'baz';  count  ;
}
  • Related