By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,571 Members | 952 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,571 IT Pros & Developers. It's quick & easy.

regular expression and case specificality

P: 4
Can anyone tell me how to write a regular expression that will match strings that either has only lower case or only upper case characters in it. For example, it will match AM, PM, am or parrot but not match Am, aM, Pm or Parrot.
Dec 9 '12 #1
Share this Question
Share on Google+
5 Replies

Rabbit
Expert Mod 10K+
P: 12,441
The | character will let you logically OR two conditions. Create one for just lower case characters and one for just upper case characters. Don't forget to set the ignore case to off.
Dec 9 '12 #2

P: 4
Hi Rabbit, thanks for the answer.

I have actually been trying to use the OR before itself, but then I understood that I am doing wrong when I look for lower case characters itself.

I thought the expression : em=re.compile('[a-z]')
will give the correct match for string with lower case only characters, but it is not. It gave the string match for strings like 'asEer'.

Can you please tell me the way to make the regex search for characters throughout the string for lower case characters?
Dec 9 '12 #3

P: 4
I can actually do this in the following expression:

re.match('[a-z]{2}|[A-Z]{2}','ab')

in which the {2} gives the length of the string to be matched. But is there anyway I can make the length of the string to be a variable, like

c=len(str)
re.match('[a-z]{c}|[A-Z]{c}','ab')

where variable 'c' is the length of the string. This doesnt work and 're' is not able to take a variable name inside the {}
Dec 9 '12 #4

Rabbit
Expert Mod 10K+
P: 12,441
There's no need to specify a length. You can use a * to match 0-infinite characters or a + to match 1-infinite characters. Then you just need to couple it with the ^ and $ characters. Where ^ demarcates the beginning of the string and $ demarcates the end of the string.
Dec 9 '12 #5

P: 4
thanks man. i added all ^,$,+ as u said. it worked.
Dec 9 '12 #6

Post your reply

Sign in to post your reply or Sign up for a free account.