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.
regular expression and case specificality
Collapse
X
-
Tags: None
-
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?Comment
-
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 {}Comment
-
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.Comment
-
Comment