3

underlying question: Is there a way to operate on text within a regex match? I.e. is there an analog to the 'g' command that operates on match substrings instead of lines

usecases: One example of this would be if you replace a pattern within a pattern without a huge amount of regex gymnastics (which are often possible with much effort). A specific example might be replace spaces with tabs but only in text matching a regex.

field1 field2 field3 field4 field with spaces

Another specific example would be if you wanted to replace - with _ but only in text inside quotes

You should name your file [something something something]
and name their file [a b c d] 

1 Answer 1

6

Maybe your solution is to use a sub-replace-expression (:h sub-replace-expression)

For example in your first example let's say that I want to replace spaces with underscores (because it's more visual in this answer) but only in the last field field with spaces:

field1 field2 field3 field4 field with spaces

I could use this command:

:s/field w.*/\=substitute(submatch(0), '_', ' ', 'g')/

 s/                                                     Substitution command
   field w.*                                            Make the substitution only on the part of the string you want to match
            /
             \=                                         Replace with an expression
               substitute(           , ' ', '_', 'g')   Use the substitution() function to replace spaces with underscore
                          submatch(0)                   Give the matched string as parameter of substitute()

This will result in

field1 field2 field3 field4 field_with_spaces

This idea is to use the substitute() function inside the replacement part of the :s command. submatch(0) is a reference to the pattern matched by :s.

In the same idea to replace something something something by something_something_something in your second example you could do this:

:s/\[.*\]/\=substitute(submatch(0), ' ', '_', 'g')/

You might want to read the following help topics:

1
  • 1
    That looks super useful! That seems to be pretty close to ideal. I'll just leave the question open for a short while longer in case there are any other interesting solutions.
    – Catskul
    Oct 15, 2018 at 16:00

Your Answer

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

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