Regex for everything before last forward or backward slash

后端 未结 3 1403
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 17:16

I need a regex that will find everything in a string up to and including the last \\ or /.

For example, c:\\directory\\file.txt should result in c:\\directory\\

相关标签:
3条回答
  • 2020-12-09 17:23

    If you're using sed for example, you could do this to output everything before the last slash:

    echo "/home/me/documents/morestuff/before_last/last" | sed s:/[^/]*$::
    

    It will output:

    /home/me/documents/morestuff/before_last
    
    0 讨论(0)
  • 2020-12-09 17:26

    Try this: (Rubular)

    /^(.*[\\\/])/
    

    Explanation:

    ^      Start of line/string
    (      Start capturing group
    .*     Match any character greedily
    [\\\/] Match a backslash or a forward slash
    )      End the capturing group  
    

    The matched slash will be the last one because of the greediness of the .*.

    If your language supports (or requires) it, you may wish to use a different delimiter than / for the regular expression so that you don't have to escape the forward-slash.

    Also, if you are parsing file paths you will probably find that your language already has a library that does this. This would be better than using a regular expression.

    0 讨论(0)
  • 2020-12-09 17:46

    ^(.*[\\\/])[^\\\/]*$

    0 讨论(0)
提交回复
热议问题