regular expression and case specificality

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shantharam
    New Member
    • Dec 2012
    • 4

    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.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    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.

    Comment

    • shantharam
      New Member
      • Dec 2012
      • 4

      #3
      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

      • shantharam
        New Member
        • Dec 2012
        • 4

        #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 {}

        Comment

        • Rabbit
          Recognized Expert MVP
          • Jan 2007
          • 12517

          #5
          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

          • shantharam
            New Member
            • Dec 2012
            • 4

            #6
            thanks man. i added all ^,$,+ as u said. it worked.

            Comment

            Working...