Search code examples
regexreplacepartial-matches

How can search and replace strings in vim and emacs be configured to work on partial or inexact matches?


I need to search and replace on strings which are partial matches and I have a contrived example below. The example below is the html from a help guide that I want to copy to add my own web page.

Open Link
Open Link in Background Tab
Upload Link
Open Link in Foreground Tab
Open Link in New Window
Download Link
Open Link in Incognito Window

Assuming I want to put the information in a Markdown or Asciidoctor table, requiring | before the lines beginning with for Open and append | after them, but ignore the other lines ie those starting with Upload and Download

How would I construct the search and replace string so it would only operate on the lines beginning with Open? Inserting | would be straightforward, but doing for the $ regex for appending | only for the lines starting with Open would be the problem.

Is it also possible to do a search and replace on both sides at one go, ie do the insert and append in a single command, or would that require a script of some kind ?(I can make this a separate question)


Solution

  • s/^\(Open.*\)/|\1|/
    

    The \( and \) enclose a pattern match to be remembered (you can have more than one \( and \) in the match pattern), and the \1 in the replacement text uses the remembered text.