0

I'm trying to write a regex that matches all spaces except those enclosed in quotes. I found solutions on the Internet for various programming languages, for example, here, but I am having trouble converting this to Vim regex:

\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)
4
  • 1
    Welcome to Vi and Vim! Please edit to include the specific regular expression you're having trouble translating (and its flavor, if you know it). Having links is a great bonus, but we want the question to stand on its own even if the links die.
    – D. Ben Knoble
    Jul 15 at 15:41
  • 2
    Thank you! I had a link to regex101 before, but it doesn't seem to be very noticeable, I duplicated the regex in the post too.
    – Shatur95
    Jul 15 at 17:17
  • the regex is not Vim Regex! Jul 15 at 19:47
  • @ChristianBrabandt, I know, it's ECMA Script Regex. And I need to convert it to Vim Regex :)
    – Shatur95
    Jul 15 at 19:49
1

The positive look-ahead (?= is \@= in Vim regex, non-capturing groups are \%(\) and capturing-groups are \(\). That would make your pattern:

\s\%(\%([^'"`]*\(['"`]\)[^'"`]*\1\)*[^'"`]*$\)\@=

There is a nice summary for comparing Perl compatible patterns with Vims in the help :h perl-patterns:

Capability in Vimspeak in Perlspeak
force case insensitivity \c (?i)
force case sensitivity \C (?-i)
backref-less grouping \%(atom\) (?:atom)
conservative quantifiers \{-n,m} *?, +?, ??, {}?
0-width match atom\@= (?=atom)
0-width non-match atom\@! (?!atom)
0-width preceding match atom\@<= (?<=atom)
0-width preceding non-match atom\@<! (?<!atom)
match without retry atom\@> (?>atom)

That helps translating patterns.

2
  • Thank you a lot! Did not know about :h perl-patterns:! I have a related question. If I put this into the following function: echo split('text "text"', "\\s\\%(\\%([^'\"`]*\\(['\"`]\\)[^'\"`]*\\1\\)*[^'\"`]*$\\)\\@="), I will have the following results: ['text', '"text"'] (double quotes captured). But if I use this expression in search (/), then the quotes are not captured. Can I avoid quotes capturing?
    – Shatur95
    Jul 15 at 21:45
  • you are splitting on that regex. That means, all non-matches will be kept in your list. Jul 16 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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