Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim regular expression to match string with prefix and suffix

Tags:

regex

vim

I want to search a string which starts with "abc" and ends with "xyz" in vim.

Below are the commands I've tried:

:1,$g/abc[\w\W]*xyz/ :1,$g/abc\[\\w\\W\]\*xyz/ :1,$g/abc*xyz/ 

"[\w\W]*" means the texts between "abc" and "xyz" can be any characters

"1,$" means the search range is from the 1st line to the last line in the file opened by vim.

I found that the search pattern

abc[\w\W]*xyz  

works in https://regex101.com/

why does it fail in vim?

like image 228
Brian Avatar asked Jun 22 '15 08:06

Brian


People also ask

How do I match a pattern in Vim?

In normal mode, press / to start a search, then type the pattern ( \<i\> ), then press Enter. If you have an example of the word you want to find on screen, you do not need to enter a search pattern. Simply move the cursor anywhere within the word, then press * to search for the next occurrence of that whole word.

Does VIM use regex?

Using Regex in VimMany of Vim's search features allow you to use regular expressions. Some of them are: The search commands ( / and ? ) The global and substitute command-line (ex) commands ( :g and :s )

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.

How do I match a pattern in regex?

Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .


2 Answers

The command below should work unless "any character" means something different for you than for Vim:

:g/abc.*xyz 
  • . means "any character except an EOL".
  • * means "any number (including 0) of the previous atom".
  • 1,$ could be shortened to %.
  • :global works on the whole buffer by default so you don't even need the %.
  • The closing / is not needed if you don't follow :g/pattern by a command as in :g/foo/d.
like image 94
romainl Avatar answered Sep 21 '22 09:09

romainl


Once the file gets too large (say, 1GB), ":g/abc.*xyz" becomes quite slow.

I found that

cat fileName | grep abc | grep xyz >> searchResult.txt 

is more efficient than using the search function in vim.

I know that this method may return lines that start with "xyz" and end with "abc".

But since this is a rare case in my file(and maybe this doesn't happen quite often for other people), I think I should write this method here.

like image 42
Brian Avatar answered Sep 23 '22 09:09

Brian