DEV Community

loading...
Cover image for How to flip array keys and values in the code editor?

How to flip array keys and values in the code editor?

insolita profile image Insolita ・1 min read

Easy, with regex search!

  • Press Ctrl+R for show replace bar
  • Enable regex mode (button looks like .* near search field)
  • Use regex in search field: '(.+)'\s=>\s'(.+)',
  • Use expression for replace: '$2' => '$1',

You can see a tooltip with a value that will be after replace

Alt Text

It is possible even you have different quotes and spaces between arrow

Use regex
(?:'|")(.+)(?:'|")\s{0,}=>\s{0,}(?:'|")(.+)(?:'|"),

And the same replace expression '$2' => '$1',

Alt Text

Named capture groups also available:

Use regex
(?:'|")(?<src>.+)(?:'|")\s{0,}=>\s{0,}(?:'|")(?<tgt>.+)(?:'|"),

And the same replace expression '${tgt}' => '${src}',

Discussion (1)

pic
Editor guide
Collapse
voyeg3r profile image
Sérgio Luiz Araújo Silva

As a test I have tried on vim

/\v^('\w+')( .. )('\d+'),
:%s//\3\2\1,
Enter fullscreen mode Exit fullscreen mode

OBS: I have used the caret as if the pattern started at the begining of line but we can also cosider the space optional

/\v^(\s+)?('\w+')( .. )('\d+'),
:%s//\1\4\3\2
Enter fullscreen mode Exit fullscreen mode

Another tip: Using neovim we have the "inccommand" that allow us to match our regex icrementally. Then we can refer to our search simply by using //