87

Suppose I search on VS Code the terms 'word1 word2'. Then it finds all the occurrences where 'word1' is followed by 'word2'. In reality I want to find all the files where word1 and word2 occur, but they don't have to be consecutive. How can I do it?

9 Answers 9

87

Use regex flag and search for (word1[\s\S\n]*word2)|(word2[\s\S\n]*word1)


Made a small extension based on @tonix regex:

https://marketplace.visualstudio.com/items?itemName=usernamehw.search

10
  • You will need some word boundaries in there too '\b' unless having word1 or word2 within another word like 'backword1' for example is not a problem for you. And I have to use \\n to get it to work in the search across files panel.
    – Mark
    Apr 20, 2018 at 16:21
  • 4
    Genius! (I will not learn regex any time soon despite its usefulness.)
    – ThaJay
    Oct 12, 2018 at 10:27
  • 3
    Can we constrain this so that all words must be on the same line? Update, this seems to work: (word1[\s\S]*word2)|(word2[\s\S]*word1)
    – Jonny
    Feb 27, 2019 at 4:08
  • 2
    @Nikhil here you are: \s - match any whitespace character \S - match any non-whitespace character \n - match a linefeed character [\s\S\n] - match exactly one of the above three [\s\S\n]* - match zero or more of any of the above three - that is, in effect, "anything at any length". In theory \s should also match \n, but this does not work in the VS Code search field. May 16, 2019 at 12:17
  • 1
    This can get really out of hand when you have more than two terms.
    – Micah B.
    Jun 30, 2022 at 20:27
53

Here is also a simple way for simple needs - use this as regex

(word1)|(word2)|(word3)  

It may not cover some cases, but has been working fine for me, and easy to remember to type it in.

3
  • This should be marked as the answer. It's the simplest working solution presented so far, and handles only what the question was asking for.
    – Pulseczar
    May 13, 2020 at 13:13
  • 30
    This matches OR. It was asked for AND. I used Alex' answer instead.
    – Wumms
    May 15, 2020 at 8:16
  • 1
    Good point, these are different use cases. This regex I use when I want to highlight all the keywords in a file May 16, 2020 at 14:31
12

To apply logical and (?=.*word1)(?=.*word2)(?=.*word3)

To apply logical or (word1)|(word2)|(word3)

2
  • 6
    This only finds them if they are on the same line. Not in the same file as requested.
    – Mark
    Feb 22, 2022 at 20:47
  • simple and easy to understand. thank you Oct 11, 2022 at 4:07
8

VSCode has an open issue to support multiple searches. You may want to get on there and push them a little.

3
  • This is now supported, you can search for the term then open in editor and use ctrl + f to search the search results thanks @pushkin Mar 23, 2021 at 15:46
  • just posted an answer for this so it's easier in the future but you could probably edit this answer Mar 23, 2021 at 15:47
  • 1
    This is not what the OP requested.
    – Deci
    Jun 19 at 14:07
5

For you guys,

if you want to search for multiple words (more than 2) at once in a single file and all the words must appear in the file at least once (logical AND), you can use the following regex which leverages lookahead assertions:

^(?=[\s\S\n]*(word1))(?=[\s\S\n]*(word2))(?=[\s\S\n]*(word3))(?=[\s\S\n]*(word4))[\s\S\n]*$

A global search with this pattern will only return all the files that contain word1 AND word2 AND word3 AND word4 in any order (e.g. word4 may appear at the beginning and/or word2 may appear at the end of the file).

I also wrote a little Python CLI helper which creates the regex automatically for you given the patterns you want to AND (though creating the regex by hand is pretty straightforward).

Copy the following code, paste it in a new file and save it somewhere on your machine (I've called it regex_and_lookahead.py). Then make the file executable with chmod +x ./regex_and_lookahead.py (important, I used Python 3.6, the literal prefix f -> f'(?=[\s\S\\n]*({arg}))' won't work in previous versions):

#!/usr/bin/env python
from sys import argv

args = argv[1:]
regex = '^'
for arg in args:
    regex += f'(?=[\s\S\\n]*({arg}))'
regex += '[\s\S\\n]*$'

print(regex)

Usage:

./regex_and_lookahead.py word1 word2 word3 word4

Will generate the above regex. You can also use it to generate more complex regexes cause each parameter can have regex characters in it!

As an example:

./regex_and_lookahead.py "pattern with space" "option1|option2" "\bword3\b" "(repeated pattern\.){6}"

Will generate the following regex:

^(?=[\s\S\n]*(pattern with space))(?=[\s\S\n]*(option1|option2))(?=[\s\S\n]*(\bword3\b))(?=[\s\S\n]*((repeated pattern\.){6}))[\s\S\n]*$

Which will match a file if and only if all of the following conditions are true:

  • There's at least one occurrence of the string pattern with space;
  • There's at least one occurrence of either option1 or option2;
  • There's at least one occurrence of the word word3 delimited by word boundary assertions;
  • There is at least one occurrence of the string repeated pattern. repeated 6 times (i.e.: repeated pattern.repeated pattern.repeated pattern.repeated pattern.repeated pattern.repeated pattern.).

As you can see, the sky is the only limit. Have fun!

3
  • your regex doesn't seem to work in the VS Code sidebar Search. Does it work on your end? The VS Code sidebar Search uses the Rust Regex engine. Is your regex written in that flavor?
    – smizzlov
    Mar 21, 2021 at 14:59
  • It used to work in 2019. Honestly I didn't try to use this regex after a while and I don't know if it works now as VS Code had several updates. What error do you get?
    – tonix
    Mar 22, 2021 at 9:40
  • I'm not getting any errors, but the search doesn't match with any files, even though there are files in my workspace containing the search terms. I'm using VS Code 1.54.3.
    – smizzlov
    Mar 23, 2021 at 20:57
3

This extension: Find and Transform, I am the author, makes it quite easy to do any number of sequential searches across files only using the files from previous search results for future searches.

There is a variable ${resultsFiles} that resolves to those previous search results files and can be used in the "filesToInclude" argument. Here is a sample keybinding

{
  "key": "alt+b",
  "command": "runInSearchPanel",
  "args": {
    
    "find": ["first", "second"],
    "delay": 2000,              // necessary to allow results to populate
    // delay may need to be longer if you are searching a lot of files 

    "replace": ["", "knuckles"],   // optional
    
    "filesToInclude": ["", "${resultsFiles}"],
    "filesToExclude": "Users\\Mark\\AppData\\Roaming\\Code\\User\\keybindings.json",
    
    "isRegex": true,

    // so that the first search will be triggered and produce results
    "triggerSearch": true,

    "triggerReplaceAll": [false, true]   // optional
  }
}
  1. "find": ["first", "second"], : search for first and then search for second
  2. "filesToInclude": ["", "${resultsFiles}"], : clear the filesToInclude on the first search, on second search use the resultFiles from the first search
  3. You can do as many sequential searches as you like
  4. The finds can be regex's and as complex as you wish

perform sequential searches using the files only from previous searches

2

This is now supported, you can search for the term then open in editor and use ctrl + f to search the search results thanks @pushkin

5
  • I think that in this case, the second search is done file-by-file right? If so, this is not very efficient when more than a handful files are returned. May 30, 2022 at 18:37
  • Not really, it opens one new file with all the occurrences and you search in that file May 31, 2022 at 16:01
  • 1
    Thanks ! But doesn't the open in editor option presents only a few lines around each occurrence and not the whole files? Such that the ctrl+f is limited to those few lines within each file? I might have gotten something wrong on my end. Jun 1, 2022 at 14:55
  • yes that is correct, not a perfect solution... Jun 1, 2022 at 15:32
  • My initial search gets a hit of over 2000 files. I do not want to then open all of those (I don't think it even could) for the second search.
    – trismi
    Nov 10, 2022 at 15:33
2

The original question asked to do a single search for files containing two separate words in the same file. Below is what I do to search for two (or more) words in the same file by using multiple searches.:

  1. Search Like you normally do
  2. Click on "Open in editor" enter image description here
  3. Adjust the context line count. (The higher the context count the more you can search for that second term, but the more non relevant searches you bring in) ,
  4. Hit Cmd + F (or equivalent if not on mac) and search there. In the image below I have narrowed it down to 53 hits. I can manually skip through until I find it. enter image description here

Need even more Fine tuning?

  1. Same Steps as 1 - 3
  2. Copy the contents to a file. (In the image below I saved it to a file called haystack.ts)
  3. Search there for a third word. (In the image below I have now narrowed it down to 7 searches.) enter image description here
1
  • 1
    Great! Many thanks for this info.
    – Fernando
    Jun 9 at 7:32
-1

Try Open new Search Editor command, through command pallete, You can map it to any keybinding you'd like in the Keybindings Editor. I mapped to cmd+shift+i

enter image description here

This is helpful for me!

There is one more way, using up/ down arrow key in search editor, moves us across our search history, even this is useful,

It needs a little bent of mind to accept that it is equivalent to having multiple search editors (what IntelliJ etc provides) but without persistence!

2
  • This does not address the question. The question regards a single search for files containing two separate words in the same file, not separate search results for two different words across all files.
    – evan.bovie
    Sep 29, 2021 at 19:42
  • the answer will still be useful addition to this question, therefore not removing it. Sep 30, 2021 at 11:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.