正则表达式匹配像<A>、<BB>、<CCC>这样的标签.但不是<ABC> [英] Regex to match tags like <A>, <BB>, <CCC> but not <ABC>
本文介绍了正则表达式匹配像<A>、<BB>、<CCC>这样的标签.但不是<ABC>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个正则表达式来匹配看起来像 、
、
的标签,但是不是
、
、<>
.所以标签必须由相同的大写字母组成,重复.我试过 <[A-Z]+>
,但这不起作用.当然我可以写类似 <(A+|B+|C+|...)>
之类的东西,但我想知道是否有更优雅的解决方案.
I need a regex to match tags that looks like <A>
, <BB>
, <CCC>
, but not <ABC>
, <aaa>
, <>
. so the tag must consist of the same uppercase letter, repeated. I've tried <[A-Z]+>
, but that doesn't work. of course I can write something like <(A+|B+|C+|...)>
and so on, but I wonder if there's a more elegant solution.
推荐答案
你可以使用这样的东西 (see这个在 rubular.com 上):
You can use something like this (see this on rubular.com):
<([A-Z])\1*>
这使用捕获组和反向引用.基本上:
This uses capturing group and backreference. Basically:
- 您使用
(pattern)
来捕获"匹配 - 然后您可以在您的模式中使用
\n
,其中n
是组号,以引用"该组匹配的内容
- You use
(pattern)
to "capture" a match - You can then use
\n
in your pattern, wheren
is the group number, to "refer back" to what that group matched
所以在这种情况下:
- 第 1 组捕获
([A-Z])
,紧跟在<
之后的大写字母 - 然后我们看看是否可以匹配
\1*
,即零个或多个相同的字母
- Group 1 captures
([A-Z])
, an uppercase letter immediately following<
- Then we see if we can match
\1*
, i.e. zero or more of that same letter
这篇关于正则表达式匹配像<A>、<BB>、<CCC>这样的标签.但不是<ABC>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文