0

I have a document that contains lines like

![My title](/path/to/image.jpg)

This is the format for images in Markdown.

I have constructed a regular expression which I believe should be able to find the image tags:

!\[(.*)\]\((.+)\)

But when I try the command /!\[(.*)\]\((.+)\), I get E486: Pattern not found: !\[(.*)\]\((.+)\).


Motivation

I am trying to do this to change how images are presented in my Hugo static site. I want to be able to search and replace everywhere in a file with

%s/!\[(.*)\]\((.+)\)/{{< figure alt="\1" src="\2" >}}/

If it matters, I'm using Vim version 8.0.1283.

1
  • Please use the correct regular expression items for Vim. So if you want to capture a group, you need to use \(\) instead of () and for capturing at least one of the previous items, you need to use \+ instead of +. May 23, 2019 at 5:59

2 Answers 2

1

I use "very magic" setting (\v) so that I can use normal regex patterns and not have to convert it into vim's awkward regex format.

First, I would do search as the original regex search term, but prepend with \v to enable "very magic" regex setting:

/\v!\[(.*)\]\((.+)\)

After testing it to make sure it is working correctly, I'd finally do search/replace operation by:

:%s/<ctrl-r>//{{< figure alt="\1" src="\2" >}}/

  • <ctrl-r>/ will paste the original search regex, so you don't have to retype it.

Result will be:

:%s/\v!\[(.*)\]\((.+)\)/{{< figure alt="\1" src="\2" >}}/ 
1
  • In fact, :s//replacement uses the previous search pattern. No register insert necessary.
    – D. Ben Knoble
    Jun 28, 2019 at 16:11
0

Vim doesn't require escaping of parentheses by default.

As Christian says:

[I]f you want to capture a group, you need to use \(\) instead of () and for capturing at least one of the previous items, you need to use \+ instead of +.

Using this modification, my regular expression becomes

!\[\(.*\)\](\(.\+\))

The parentheses which were part of capture groups have been escaped, as has the +, and the parentheses which were literals have been unescaped. This new expression works as intended.

My full search and replace is now

:%s/!\[\(.*\)\](\(.\+\))/{{< figure alt="\1" src="\2" >}}/

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.