VSCode - find and replace with regexp, but keep word in the middle

Viewed 105

I have multiple occurrences of

AppLocalizations.of(context).translate('WORDING_STR')

in my code, that I would like to change to

LocaleKeys.WORDING_STR.tr()

Is it possible to do it with regular expressions, so I can keep whatever is in the code as WORDING_STR?

example:

Replace AppLocalizations.of(context).translate('finish_status') to LocaleKeys.finish_status.tr()

2 Answers

In VSCode, try this regex to find the occurrences:

AppLocalizations\.of\(context\)\.translate\('(\w+)'\)

And this one to replace:

LocaleKeys.$1.tr()

Explanation

\w means match a word character only. And because it's wrapped around parens it creates a capturing group that we can back-reference with $1 to use the captured word in the first group to replace the text. Check it out on https://regex101.com/ to get a detailed explanation of all kinds of regexes.

Screenshots

Before After
Screenshot before Screenshot after

Thanks @lepsch for solution to my question.

added, In my case I found that i had prettier in my vscode that format my code like this

AppLocalizations.of(context)
                                    .translate('WORDING_STR')

Prettier add whitespace in my code

The solution is add whitespace [\s\n] in regex so the result will still match the case

AppLocalizations\.of\(context\)+[\s\n]+\.translate\('(\w+)'\)

The Result: The Result

But unfortunately this will make mess if i had code like this: enter image description here

Related