Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for matching alternating case letters

Tags:

regex

I would like to detect the following sequences:

a
aA
aAa
aAaA
...

where a~[a-z] and A~[A-Z], the case alternates and the first letter is always lower-case.

Thanks,
Tom

like image 885
Tom Avatar asked Apr 17 '10 20:04

Tom


People also ask

How to match capital letters in regex?

Using character sets For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter.

How do you match periods in regex?

The period (.) represents the wildcard character. Any character (except for the newline character) will be matched by a period in a regular expression; when you literally want a period in a regular expression you need to precede it with a backslash.


2 Answers

[a-z]([A-Z][a-z])*[A-Z]?
like image 115
tanascius Avatar answered Oct 18 '22 05:10

tanascius


The regex that @tanascius gave is fine, and based on that, a shorter one could be:

([a-z][A-Z])*[a-z]?

A major difference is that this one will match the empty string. I wasn't sure from the examples if that was allowed.

like image 36
JXG Avatar answered Oct 18 '22 06:10

JXG