RE exact match

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nk28
    New Member
    • Jan 2010
    • 26

    RE exact match

    I am having problem in re module of python.

    when i do a call of match function it returns true if first of the expression is true.

    For Eg :- Expression like ([a-z]+([+][a-z])*) to denote
    (a-z)^* + (a-z)^* returns true for ab+ and ab+12

    What is the correct method to match exact expression in re module of python ??

    That is above 123 should not be accepted but it still is.........

    Thanxx a lot !!
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    If I understand your question correctly, the following expression will match 'ab+' and 'ab+df' but will not match 'ab+12':
    Code:
    patt = r'([a-z]+)[+]([a-z]*)$'

    Comment

    • Glenton
      Recognized Expert Contributor
      • Nov 2008
      • 391

      #3
      These docs should help. I don't entirely understand your question, as it's not clear (to me at least) what is regular expressions and what is strings you're trying to match to!

      But * means "0 or more of the preceding character(s)"
      and + means "1 or more of the preceding character(s)"

      Comment

      • nk28
        New Member
        • Jan 2010
        • 26

        #4
        Doubt

        What i want to know is if there 's a function in python that does exact matching of regular expression.

        The docs say that the match function returns true if some part of it gets accepted.....

        Thanxx a lot....

        Comment

        • Glenton
          Recognized Expert Contributor
          • Nov 2008
          • 391

          #5
          The more detailed docs give you the answer, I think.

          But @bvdet has got the answer as usual. The $ character matches the end of the string. So with the pattern as:

          Code:
          pat=r'([a-z]+)[+]([a-z]*)$'
          This returns a match:
          Code:
          In [3]: re.match(pat,"ab+cd")
          Out[3]: <_sre.SRE_Match object at 0x992d3c8>
          But these do not:
          Code:
          In [4]: re.match(pat,"ab+12")
          
          In [5]: re.match(pat,"ab1"+"ab")
          
          In [6]: re.match(pat,"ab+cd1234")

          Comment

          Working...