Question:
Task from the book. Write a regular expression that checks if a string variable matches a rule:
- there is at least one uppercase letter
- there is at least one lowercase letter
- 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.
Answer:
/([a-z][A-Z])|([A-Z][a-z])/
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";
}
}
conclusion:
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.