Reputation: 1363
I need to remove brackets around a component name while importing it:
Example string:
import { Component } from 'components/components1
Regex used in the Find field:
import (\{(.*?)\}) from 'components/(componentgroup|componentgroup2|componentgroup3)
Pattern used in Replace field:
import $1 from 'ui/$2
This way I can select all occurrences, but can't get the expected results in the text.
Is there any other way than doing it manually?
I have also this regex, matches without brackets:
([^{}\s](?:[^{}]*[^{}\s])?)
Upvotes: 0
Views: 1209
Reputation: 626893
Your regex is fine, although you could write it with a word boundary at the end to make sure you match the components as whole words:
import (\{(.*?)\}) from 'components/(componentgroup|componentgroup2|componentgroup3)\b
Next, your replacement pattern must be
import $2 from 'ui/$3
where Group 2 comes first, then Group 3.
See the regex demo.
A bit more enhanced version:
import\s+\{\s*(.*?)\s*\}\s+from\s+'components\/(componentgroup|componentgroup2|componentgroup3)\b
Replace with import $1 from 'ui/$2
.
See this regex demo.
Due to \s*
in \{\s*(.*?)\s*\}
the package name will be trimmed from whitespace, and \s+
will ensure the match will occur even if there are any kind and amount of whitespace between the words. Note Visual Studio Code regex is a bit specific and \s
does not match line break chars unless there is \r
or \n
in the pattern, so, in this case, \s
won't go across lines.
Upvotes: 2