tags:

views:

56

answers:

1

hi all,

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. thanks.

+7  A: 

You can use something like this (see this on rubular.com):

<([A-Z])\1*>

This uses capturing group and backreference. Basically:

  • You use (pattern) to "capture" a match
  • You can then use \n in your pattern, where n is the group number, to "refer back" to what that group matched

So in this case:

  • 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

References

polygenelubricants
You should elaborate on why this works.
John Gietzen
@John: indeed, why not start with "what is regular expression".
SilentGhost