3 Replies - 3713 Views - Last Post: 20 August 2011 - 07:28 AM Rate Topic: -----

#1 jhar131  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 149
  • Joined: 03-February 10

Regex - Capture everything before final backslash, but..

Posted 19 August 2011 - 03:14 PM

.. there can be other backslashes in the pattern. For example, from this path:

./usr/lib64/mpich2/lib/libmpichcxx.so.1




I just want to grab:
./usr/lib64/mpich2/lib



I'm sure this can be done, but my regex powers are not strong.
Is This A Good Question/Topic? 0
  • +

Replies To: Regex - Capture everything before final backslash, but..

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4307
  • View blog
  • Posts: 12,083
  • Joined: 18-April 07

Re: Regex - Capture everything before final backslash, but..

Posted 19 August 2011 - 03:32 PM

Well the first pattern you can try is... \..*\/. What this is saying is find the part of the text which starts with a period and has any number of characters but ends with a forward slash. This will match all the way to the last forward slash because regex is naturally "Greedy". It will always want the biggest match and pass up the smaller matches.

The result will typically contain the last forward slash, so if you need to chop that, you can simply remove the last character off the result match.

:)
Was This Post Helpful? 0
  • +
  • -

#3 jhar131  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 149
  • Joined: 03-February 10

Re: Regex - Capture everything before final backslash, but..

Posted 19 August 2011 - 03:45 PM

Thanks for the response. + rep, and just for posterities sake, I had already written a working expression with that in it. To be specific, mine was:
.*\\/.*$



Although I guess the $ is redundant, as you show in your example.



ETA: I can't spell

This post has been edited by jhar131: 19 August 2011 - 03:45 PM

Was This Post Helpful? 0
  • +
  • -

#4 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 452
  • View blog
  • Posts: 796
  • Joined: 08-June 10

Re: Regex - Capture everything before final backslash, but..

Posted 20 August 2011 - 07:28 AM

No need for a regex, just use rsplit():

fullpath = './usr/lib64/mpich2/lib/libmpichcxx.so.1'

path, filename = fullpath.rsplit('/', 1)



To make it platform independent, use os.path.sep instead of '/'.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1