регулярные-выражения – Matches strings containing but not all capital letters


Task from the book. Write a regular expression that checks if a string variable matches a rule:

  1. there is at least one uppercase letter
  2. there is at least one lowercase letter
  3. these 2 characters are in a row, the order doesn't matter

For simplicity, we assume that strings do not contain newlines.

I wrote something like this: /[az]*[AZ]+[az]*/ or /[az]*[AZ]+[az]+/

It is proposed to test on strings like "fred" , "Fred" and "frEd" . I found one word that this pattern doesn't match, and that's "freD" . How to generalize a regular expression to all possible strings?

The answer in the pearl book is even worse than my solution.



Isn't that exactly what the condition is?

foreach (qw/fred FRED fRed Fred freD 1234/) {
    if (/([a-z][A-Z])|([A-Z][a-z])/) {
        print "$_ - ok\n";
    } else {
        print "$_ - bad\n";


fred - bad
FRED - bad
fRed - ok
Fred - ok
freD - ok
1234 - bad

P.S. Parentheses in the regular expression are optional, but I prefer to put them in this situation.

Scroll to Top