开发者

Regex search and replace in VI

开发者 https://www.devze.com 2022-12-19 12:06 出处:网络
I have a document with lots of <swf...>.....</swf> in it. I would like to remove all these. Using vi when i type

I have a document with lots of <swf...>.....</swf> in it. I would like to remove all these. Using vi when i type

:%s/\<swf[^\/swf>]+\/swf\>//g

I was hoping this would work, but it doesn't match开发者_如何转开发 anything.


You can remove all those from the buffer with this command:

:%s!<swf.\{-}/swf>!!

if you also have tags that might be split on two lines, you can add the \_ modifier to make . match newlines too:

:%s!<swf\_.\{-}/swf>!!

this assuming you want to remove both the tags and what they contain, if you just want to get rid of the tags and keep the content

:%s!</\?swf.\{-}>!!

Notes:

  • you don't need to escape < or >
  • you can choose whatever pattern delimiter you wish: Vim will use the first character you put after the s in the substitute command: this takes away the need to escape forward slashes in your pattern

EDIT: extending my answer after your comment

  • this is exactly like /STRING/REPLACE/g I only used a ! instead of / so that I don't have to quote the backslash in the pattern (see my second point above)
  • I didn't add the g modifier at the end since I have :set gdefault in my .vimrc since forever (it means that by default Vim will substitute all matches in a line instead of just the first, thus reverting the meaning of /g)
  • \{-} is the "ungreedy" version of the * quantifier, i.e. it matches 0 or more of the preceding atom but take as few as possible -- this helps you make sure that your search pattern will extend to the first "closing tag" instead of the last.

HTH


The problem here is that the [] is a character class, so you are telling it that between the swf opening and closing tags, the letters s, w and f cannot appear anywhere, in any order.

You could try a non-greedy match instead:

\<swf.\{-}\/swf\>

Note that . does not allow newline by default.

I don't use Vim though, so I used this guide to discover the syntax. I hope it is correct.

0

精彩评论

暂无评论...
验证码 换一张
取 消