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

前端 未结 5 595
感动是毒
感动是毒 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:43

    I see 2 quick alternatives:

    • re.match(pattern='.*pdf$', string='filename.pdf')

      Using this solution we must specify that we don't care about how the string begins. But we cannot omit the expression at the beginning. When using re.match() you must be sure to provide a regex valid for the whole string i.e. since index 0 see https://docs.python.org/3/howto/regex.html#match-versus-search

    • re.search(pattern='\.pdf$', string='filename.pdf')

      We don't care about how the string begins, we're just searching a string which ends with the extension

    Answered have been already accepted but I've personnaly needed to check the official documentation to be clear with that.

提交回复
热议问题