VSCode Search and Replace Regex

2020-02-25 07:51发布

问题:

I'm trying to do a project wide search and replace

from:

drivers[i].findElement(By.id("elementID")).click();

to:

findAndClick(driver[i], "elementID", true)

The issue is the elementID can be anything so I'm trying to wildcard search and replace with what's in the wildcard?

回答1:

You'll need to use .+? instead of * here since this uses regular expressions.

In regular expressions a dot . means "any character", the plus + means "one or more times", and the question mark ? after this means "try to match this as few as possible times" - which is useful so it won't keep matching past your quote marks

edit

To be clear though, you have to make a valid regex, which means you'll need to escape your parenthesis, dots, etc.

Here's the full solution

Find: drivers\[i\]\.findElement\(By\.id\("(.+?)"\)\)\.click\(\);

replace with: findAndClick(driver[i], "$1", true)

Note the added unescaped parentheses in there around the "wildcard" (.+) this creates a capture group in a regex, which is what translates to $1 in the replacement since it's the 1st capture group.