Regular expression in Python won't match end of a string

前端 未结 5 581
感动是毒
感动是毒 2021-02-13 12:46

I\'m just learning Python, and I can\'t seem to figure out regular expressions.

r1 = re.compile(\"$.pdf\")
if r1.match(\"spam.pdf\"):
    print \'yes\'
else:
            


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-02-13 13:29

    You've tried all the variations except the one that works. The $ goes at the end of the pattern. Also, you'll want to escape the period so it actually matches a period (usually it matches any character).

    r1 = re.compile(r"\.pdf$")
    

    However, an easier and clearer way to do this is using the string's .endswith() method:

    if filename.endswith(".pdf"):
        # do something
    

    That way you don't have to decipher the regular expression to understand what's going on.

提交回复
热议问题