Regular expression doubt

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • abby08
    New Member
    • May 2019
    • 1

    Regular expression doubt

    problem : atleast 2 char string wherein 1 char should be between a-k , second char should a number divisible by 3 and then any digit or character.

    Code:
    import re
    patt=re.compile(r"[a-k][0369][a-zA-Z0-9#]*")
    m=patt.search("aaa9#")
    if(m!=None):
        print("Matched")
    else:
        print("Not Matched")
    Why does above program gives Matched?
    Last edited by gits; May 10 '19, 11:14 AM. Reason: added code tags
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    There is an old saying, "you have to solve a problem. You decide to use regular expressions. Now you have two problems." So unless you are required to use regular expressions, it is easier and more straight forward to use if statements
    Code:
    ## atleast 2 char string
    test_string="aaa9#"
    if len(test_string > 1):
        ## wherein 1 char should be between a-k
        ## I assume this means the first character
        if "a" <= test_string[0] <= "k":
            ## second char should a number divisible by 3
    
            ## *****Your test string fails here*****
            if test_string[1].isdigit() and 0 == int(test_string[1]) % 3:
                print("Matched")

    Comment

    • Rabbit
      Recognized Expert MVP
      • Jan 2007
      • 12517

      #3
      Because the substring "a9" matches your regex. Nothing in your regex says the whole string has to conform.

      Comment

      • Luuk
        Recognized Expert Top Contributor
        • Mar 2012
        • 1043

        #4
        @Rabbit is right, and maybe a bit 'off-topic', but yesterday I was reading this on stackoverflow. which might be of interest. it's about using regular expressions … 😉

        Comment

        Working...