2

In order to overcome my irritation with quoting and comma separating words in a list, I thought I would play with Vim's search and replace to allow myself to type lists like this:

daqs = [this is a test of some cool vim stuff for creating a comma separated list of strings]

and use a regular expression to convert this line to this:

daqs = ["this", "is", "a", "test", "of", "some", "cool", "vim", "stuff", "for", "creating", "a", "comma", "separated", "list", "of", "strings", ]

I visually selected everything inside the brackets, and used the expression:

:'<,'>s/\%V\S\+[^\]]/\"&\", /g

But a trailing whitespace character seems to be following my "&" insertion, giving me this:

daqs = ["this ", "is ", "a ", "test ", "of ", "some ", "cool ", "vim ", "stuff ", "for ", "creating ", "a ", "comma ", "separated ", "list ", "of ", "strings", ]

Note that the final word does not have a space at the end within the quotes. How can I match each word between the brackets without carrying around this ending whitespace?

0

2 Answers 2

3

I made it work with a different regex:

:'<,'>s/\%V[^] ]\+/\"&\",/g

decomposing:

:'<,'>s/       " start a new substitution command
\%V            " match inside the visual selection
[^] ]\+        " match everything but a space and a closing ] (1 or more time)
/              " replace with
\"&\",         " the quoted matched group followed by a space and a ,
/g             " replace globally
1
  • 2
    Thanks! This works exactly as I had hoped. Thanks for the decomposition, it's extremely helpful
    – ncoish
    Apr 26, 2016 at 15:47
4

Here is a vimscript-based alternative, just for the fun of it:

:s/\[\(.*\)\]/\=string(split(submatch(1), " "))

See :help sub-replace-expression, :help submatch(), :help string(), and :help split().

4
  • Nice, do you see any practical use of your version instead of the "simple" one ? (performance/reusability/...)
    – nobe4
    Apr 26, 2016 at 15:55
  • 1
    Using vimscript probably makes it a bit faster but by a small margin if any. Other than that, it's just for fun.
    – romainl
    Apr 26, 2016 at 19:12
  • This is a great solution, but it single quotes the resulting strings. This is fine for my application, but do you know if there's a way to change the default of "string" to double quote strings? Otherwise another pass to search and replace quotes is necessary
    – ncoish
    Apr 28, 2016 at 17:23
  • 1
    No, the single quotes can't be changed to double quotes. But, as I said, "just for the fun of it".
    – romainl
    Apr 28, 2016 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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