I was practicing regular expressions and attempted to write a regex which will detect
“cay” and “cabby” and also “catty”. I feel this is correct:
ca(([bt])\1*)?y
but on trying this on RegexBuddy, I see that it only matches “cay”. Can anyone find the problem?
thanks, Mishal
You must count parentheses correctly:
would capture
cay,cabby,catty.The simpler:
would capture
cay,cabby,cattyexplicitly.PS: I thought quantifying back-references (as in
\2*) was not possible, but in fact it is. If you want to match any amount of only"t"or only"b", the following would be okay:matches
cay,caby,cabby,cabbbbbbbbbbbbbbbbbbbby,catttty, etc. It can be simplified to the equivalent:because such a construct
(x*)?is redundant.