I’m just learning Python, and I can’t seem to figure out regular expressions.
JavaScript
x
6
1
r1 = re.compile("$.pdf")
2
if r1.match("spam.pdf"):
3
print 'yes'
4
else:
5
print 'no'
6
I want this code to print ‘yes’, but it obstinately prints ‘no’. I’ve also tried each of the following:
JavaScript
1
10
10
1
r1 = re.compile(r"$.pdf")
2
3
r1 = re.compile("$ .pdf")
4
5
r1 = re.compile('$.pdf')
6
7
if re.match("$.pdf", "spam.pdf")
8
9
r1 = re.compile(".pdf")
10
Plus countless other variations. I’ve been searching for quite a while, but can’t find/understand anything that solves my problem. Can someone help out a newbie?
Advertisement
Answer
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).
JavaScript
1
2
1
r1 = re.compile(r".pdf$")
2
However, an easier and clearer way to do this is using the string’s .endswith()
method:
JavaScript
1
3
1
if filename.endswith(".pdf"):
2
# do something
3
That way you don’t have to decipher the regular expression to understand what’s going on.