0

I'm using a vim script to quickly edit some text. I have a large list from an api endpoint that looks like this:

 save: presets.api + 'campaign/:campaignId/settings', accept: presets.api + 'campaign/:campaignId/acceptContractTerms', list: presets.api + 'campaign/:campaignId/helloSignTemplates', create: presets.api + 'campaign/:campaignId/helloSignTemplates/create', post: presets.api + 'campaign/:campaignId/helloSignTemplates', patch: presets.api + 'campaign/:campaignId/helloSignTemplates/:templateId', delete: presets.api + 'campaign/:campaignId/helloSignTemplates/:templateId', 

I'd really like to delete all text that is not inside single quotes. What would the vim regex command for that be?

2 Answers 2

3

It's arguably even easier to do this without regular expressions, by using the :normal command. To delete the text on one line you would type: df';D, which deletes to the first quote (df'), moves to the next quote (;), and then deletes the rest of the line (D). So to do this on the entire file with one command, run:

:%norm!df';D 

If you wanted to keep the quote marks as well, the command is slightly longer, but just as simple:

:%norm!dt';llD 
2

If it's given that only one single-quoted text will appear in a line, then the regex is simple:

%s:\v.{-}('.{-}').*:\1: 
  • %s: run :h :substitute over the whole buffer
  • :: delimiter
  • \v: use :h /magic mode
  • pattern to be replaced
    • .{-}: select least-possible characters
    • '(.{-})': select text wrapped in single-quotes and mark it as sub-expression (see :h /\()
    • .*: match any text as many number of times as possible
  • :: delimiter
  • \1: replace the matched pattern with the first sub-expression (which is the text wrapped in single-quotes.

This will leave only the first single-quoted text and delete everything else. If two or more single-quoted text exist in a line, this regex will not be functional. We can devise another regex for that case, but since that is slightly more difficult to come up with, I'm leaving it as to-be-done only if the OP expresses they require it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.