Reputation: 1376
I have a string like that :
//some.path/again/and/again/foo/bar/ABC_blahblah.xls
I want to retreive ABC
which is always between a /
and a _
I tried so far :
path.scan(/\/(.*)_/).last.first
but I get //some.path/again/and/again/foo/bar/ABC
I see that ruby matches the first /
. How can I get what is between the last \
and the _
?
Thanks in advance.
Upvotes: 1
Views: 1075
Reputation: 11234
path = "//some.path/again/and/again/foo/bar/ABC_blahblah.xls"
path.scan(/(?:[^\/])*(?=_)/).reject(&:empty?)
Upvotes: 0
Reputation: 160551
Don't use a full regex to break down a file path. Instead, rely on some pre-written code. The reason is, if you move your code to a different OS, such as Windows, it's possible you'll get file paths using different path separators. Ruby's IO and File classes are aware of the differences and will automatically adjust for you.
Compare your pure regular expression solution to something like these:
path = '//some.path/again/and/again/foo/bar/ABC_blahblah.xls'
File.basename(path) # => "ABC_blahblah.xls"
File.basename(path)[/^([^_]+)/, 1] # => "ABC"
File.basename(path)[/^(.+)_/, 1] # => "ABC"
File.basename(path).split('_', 2).first # => "ABC"
File's basename
returns the name of the file when given a path to the file.
Upvotes: 2
Reputation: 3319
Try using \/([^\/]*)_
it will avoid having any forward slash in the captured group.
Upvotes: 1