views:

264

answers:

3

I have a file in this structure:

009/foo/bar/hi23123/foo/bar231123/foo/bar/yo232131

What i need is to find the exact match of a string; e.g. only /foo/bar among /foo/bar/hi and /foo/bar/yo

One solution came up in my mind is like to check for ending "/" for the input string. Because if there is ending "/" in the possible results, that means it got something different than only /foo/bar.

For this solution, I must say that:

input = /foo/bar

and

match input without ending "/"

How can I do this by Regex in python?

Btw, if there any other solution suggestion, you're welcome to share here.

+6  A: 

So you want /foo/bar not followed by a /? If so, then you're looking for a "negative lookahead",

r = re.compile(r'/foo/bar(?!/)')

and then r.search to your heart's content.

Alex Martelli
A: 

If I gather correctly, what you're looking for is an exact match of the string. Using your example /foo/bar your query would look something like this:

r = re.compile(r'^/foo/bar$')

Go to http://www.regular-expressions.info/ for more information on Regular Expressions in general.

Rudisimo
Yes, this is partly true. But, what i mean in the question is, there may be multiple matches of the current string. So, I think Alex Martelli's solution is more general and what i want. Thanks anyway...
israkir
A: 

filename = "009/foo/bar/hi23123/foo/bar231123/foo/bar/yo232131"

to_find ="/foo/bar"

if to_find in filename: print "found!"

prime_number
is this what OP wants?
ghostdog74