Regular Expression to match only one angle bracket

你。 提交于 2019-11-28 10:59:41

问题


I'm looking for a regular expression that matches the '>' in

a > b > b> ... 

but not two or more angled brackets, i.e. it should not match

a>>b >> b>> ... 

I was sure to do that with lookaheads or lookbehinds, but for some reason neither

\>(?!\>) 

nor

(?<!\>)\> 

work..?

Thanks!


回答1:


Perl syntax:

/(?<!>)>(?!>)/ 

Without using lookahead or lookbehind:

/(?:^|[^>])>(?:[^>]|$)/ 



回答2:


perreal's first regex is correct. However, the second regex given in that answer subtly fails in one condition. Since it captures characters both before and after, two >s separated by a single character will not both be found.

Here is a regex which only uses forward lookaheads and doesn't have that problem:

(?:^|[^>])(>)(?:$|(?!>)) 

Edit live on Debuggex




回答3:


The issue here is that when you use the lookahead, you're matching the second > (there's no > after the second >), and when you're using the lookbehind, you're matching the first >.

You could probably use this:

[^>]>[^>] 

There's a >, with no > before or after it.

But I think that to suit what you exactly need, need to use lookaheads and lookbehinds both:

(?<!>)>(?!>) 


来源:https://stackoverflow.com/questions/16747723/regular-expression-to-match-only-one-angle-bracket

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