470,863 Members | 1,344 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,863 developers. It's quick & easy.

regular expression and case specificality

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
5 2020
Rabbit
12,516 Expert Mod 8TB
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
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
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
12,516 Expert Mod 8TB
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
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.

Similar topics

2 posts views Thread by Bryce Budd | last post: by
8 posts views Thread by Rajeev Soni | last post: by
7 posts views Thread by Chris Kennedy | last post: by
2 posts views Thread by Brian Kitt | last post: by
25 posts views Thread by Mike | last post: by
5 posts views Thread by Grzegorz Danowski | last post: by
3 posts views Thread by gast128 | last post: by
18 posts views Thread by Lit | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.