Vim: regex to match words inside angle brackets?

我是研究僧i 提交于 2019-12-23 01:56:22

问题


I want to match words inside angle brackets (html tags):

<MatchedWord></MartchedWord>

This is what I have so far:

/\v\<\w+\>

The problem is that it matches the <> too and the /.

How to do it so it only matches the word?


回答1:


You can assert matching before and after text without including that in the match via Vim's special \zs (match start) and \ze (match end) atoms:

/<\/\?\zs\w\+\ze\/\?>

I've included an optional (\?) slash on both side (e.g. </this> and <this/>. Also note that \w\+ isn't a completely correct expression for XML or HTML tags (but it can be a good-enough approximation, depending on your data).

Alternative

For most other regular expression engines, you need to use lookbehind and lookahead to achieve this. Vim has those, too (\@<= and \@=), but the syntax is more awkward, and the matching performance may be poorer.




回答2:


You dont need to escape angle brackets (square brackets are []) since they are not special characters. You can use capturing groups

<\/?(.+)>



回答3:


In a non-vim environment, this is achieved using positive lookbehind and lookahead as such:

/(?<=<).*?(?=>)/

This matches the following:

<test>         // test
</content>     // /content
<div id="box"> // div id="box"
<div id="lt>"> // div id="lt

So as you can see by the final example it's not perfect, but you are using regex on html so you get what you pay for

See the regex in action



来源:https://stackoverflow.com/questions/28608570/vim-regex-to-match-words-inside-angle-brackets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!