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.

Answer from kindall on Stack Overflow
Top answer
1 of 6
66

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.

2 of 6
35

Behaviour of re.match() and re.search()

There is one significant difference: re.match() checks the beginning of string, you are most likely looking for re.search().

Comparison of both methods is clearly shown in the Python documentation chapter called "search() vs. match()"

Special characters in regular expression

Also the meaning of characters in regular expressions is different than you are trying to use it (see Regular Expression Syntax for details):

  • ^ matches the beginning:

    (Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.

  • $ matches the end:

    Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline. foo matches both ‘foo’ and ‘foobar’, while the regular expression foo$ matches only ‘foo’. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches ‘foo2’ normally, but ‘foo1’ in MULTILINE mode; searching for a single $ in 'foo\n' will find two (empty) matches: one just before the newline, and one at the end of the string.

Complete answer

The solution you are looking for may be:

import re
r1 = re.compile("\.pdf$")  # regular expression corrected
if r1.search("spam.pdf"):  # re.match() replaced with re.search()
    print "yes"
else:
    print "no"

which checks, if the string ends with ".pdf". Does the same as kindall's answer with .endswith(), but if kindall's answer works for you, choose it (it is cleaner as you may not need regular expressions at all).

🌐
Finxter
blog.finxter.com › home › learn python blog › python endswith() tutorial – can we use regular expressions?
Python endswith() Tutorial - Can We Use Regular Expressions? - Be on the Right Side of Change
June 19, 2022 - >>> for tweet in tweets: ... if tweet.endswith(("coffee", "python")): ... print(tweet) coffee break python i like coffee · This snippet prints all strings that end with either "coffee" or "python". It is pretty efficient too. Unfortunately, you can only check a finite set of arguments. If you need to check an infinite set, you cannot use this method. Let’s check whether a tweet ends with any version of the "coffee" string. In other words, we want to apply the regex ".+coff*".
🌐
Python Examples
pythonexamples.org › python-regex-check-if-string-ends-with-specific-word
Check if String ends with Specific Word - Regex - Python
import re str = 'apple banana cherry' #search using regex for multiple possible ending words x = re.search('(cherry|banana)$', str) if(x!=None): print('The line ends with \'cherry\' or \'banana\'.') else: print('The line does not end with \'cherry\' or \'banana\'.')
🌐
W3Schools
w3schools.com › python › ref_string_endswith.asp
Python String endswith() Method
Python Examples Python Compiler ... Interview Q&A Python Training ... The endswith() method returns True if the string ends with the specified value, otherwise False....
🌐
Bobby Hadz
bobbyhadz.com › blog › python-check-if-string-endswith-regex
Check if String ends with a Substring using Regex in Python | bobbyhadz
April 10, 2024 - Copied!import re string = ... with many useful examples. You can also use the str.endswith() method to check if a string ends with a substring....
🌐
TutorialsPoint
tutorialspoint.com › how-to-match-at-the-end-of-string-in-python-using-regular-expression
How to match at the end of string in python using Regular Expression?
April 23, 2025 - To match at the end of string in Python using regular expressions, we use the $ metacharacter which anchors the pattern to the end of the string.
Find elsewhere
🌐
Sethmlarson
sethmlarson.dev › regex-$-matches-end-of-string-or-newline
Regex character “$” doesn't mean “end‑of‑string”
So if you're trying to match a string without a newline at the end, you can't only use $ in Python!
🌐
TutorialsPoint
tutorialspoint.com › how-to-check-if-string-or-a-substring-of-string-ends-with-suffix-in-python
Python String endswith() Method
September 2, 2025 - The python string endswith() method checks if the input string ends with the specified suffix. This function returns true if the string ends with the specified suffix, otherwise returns false.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.Series.str.endswith.html
pandas.Series.str.endswith — pandas 3.0.6 documentation
Equivalent to str.endswith(). ... Character sequence or tuple of strings. Regular expressions are not accepted. ... Object shown if element tested is not a string. The default depends on dtype of the array. For the "str" dtype, False is used. For object dtype, numpy.nan is used.
🌐
Python Data Science Handbook
jakevdp.github.io › WhirlwindTourOfPython › 14-strings-and-regular-expressions.html
String Manipulation and Regular Expressions | A Whirlwind Tour of Python
For the special case of checking for a substring at the beginning or end of a string, Python provides the startswith() and endswith() methods:
🌐
W3schools
w3schools.dev › python › ref_string_endswith.asp
Python String endswith() Method - W3Schools
Python Examples Python Compiler Python Exercises Python Quiz Python Server Python Interview Q&A Python Bootcamp Python Certificate ... The endswith() method returns True if the string ends with the specified value, otherwise False.
🌐
W3Schools
w3schools.com › python › python_regex.asp
Python RegEx
RegEx can be used to check if a string contains the specified search pattern. ... Python has a built-in package called re, which can be used to work with Regular Expressions.
🌐
Runebook.dev
runebook.dev › en › docs › python › library › stdtypes › str.endswith
Python's str.endswith() Explained: Troubleshooting and Regex Substitutes
The str. endswith() method is a simple and efficient way to check if a string ends with a specified suffix. It returns True if the string does end with the given suffix
🌐
Shiksha
shiksha.com › home › it & software › programming › colleges in india
Python Courses in India - Fees, Courses, Admissions
March 30, 2023 - Find 245 Python Courses and Colleges in India. Compare Fees, Courses, Student Reviews and Admission process
🌐
TutorialsPoint
tutorialspoint.com › article › python-check-whether-a-string-starts-and-ends-with-the-same-character-or-not
Python - Check whether a string starts and ends with the same character or not
def check_string_builtin(my_string): if len(my_string) == 0: return "Empty string" first_char = my_string[0].lower() if my_string.lower().startswith(first_char) and my_string.lower().endswith(first_char): return "Same character" else: return "Different characters" # Test multiple strings test_cases = ["Python", "level", "Hello", "racecar", "A"] for text in test_cases: result = check_string_builtin(text) print(f"'{text}': {result}") 'Python': Different characters 'level': Different characters 'Hello': Different characters 'racecar': Same character 'A': Same character ·