kylex
kylex

Reputation: 14406

re.search() exact comparison at end of string

Attempting to do an exact string comparison for the end of a string:

re.search(r'%s' % name1, name2, re.IGNORECASE)

So if name1 = "local/foo" and name2= "foo" the statement will return true.

However, the above test is returning true for name1 = "foo" and name2 = "foo-bar" How can I match the ends only?

Upvotes: 0

Views: 108

Answers (3)

Veedrac
Veedrac

Reputation: 60137

There's also re.fullmatch on Python 3.4. This uses \Z over $, so has a better default.

Upvotes: 1

ooga
ooga

Reputation: 15501

Another option:

name1.lower().endswith(name2.lower())

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121524

Use $ to anchor your search to the end:

re.search(r'%s$' % name1, name2, re.IGNORECASE)

You probably want to use re.escape() to make sure no metacharacters in name1 are interpreted as regular expression patterns:

re.search(r'%s$' % re.escape(name1), name2, re.IGNORECASE)

Upvotes: 3

Related Questions