0

I want to find the string enclosed by string1 and string2 and replace it with something else. I got a few lines that look something like

some_string_and_string1_some_rndom_string_string2_and_more
sme_string_and_string1_some_random_string_string2_and_more
some_string_and_string1_some_random_string_string2_and_mre
...

I thought the regex to match everything enclosed by string1 and string2 is

/^string1.*string2$

So the regex would match

string1_some_rndom_string_string2
string1_some_random_string_string2
string1_some_random_string_string2
...

But if I select the lines and try

:'<,'>s/^string1.*string2$

I get

Pattern not found: ^string1.*string2$

What am I doing wrong?

2 Answers 2

4

Don't use ^ and $. ^ is start of a line - which means that expression you're looking for needs to be at the very beginning of a line. The same goes for $, which means end of a line. In you're case there is something between ^ and string1/$ and string2, and regex expects that string1 will be first, and it finds some_string_and_ instead.

string1.*string2

should be enough.

0

Another thing to look at is if you have set nomagic in your .vimrc.

See help magic:

Examples:
after:    \v       \m       \M       \V         matches
                'magic' 'nomagic'
          $        $        $        \$         matches end-of-line
          .        .        \.       \.         matches any character
          *        *        \*       \*         any number of the previous atom

You can temporarily change it with \m (or \v):

:'<,'>s/\mstring1.*string2

or use

:'<,'>s/string1\.\*string2

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.