Reputation: 10541
How can I get the following strings to output the following?
regex = '' # help me out here guys!
'baz/foobaryfobar/'.match(regex) #=> foobaryfobar
'baz/foobar'.match(regex) #=> foobar
'baz/foobar.jpg'.match(regex) #=> foobar
'baz/foobar.png'.match(regex) #=> foobar
'baz/foobar.gif'.match(regex) #=> foobar
'baz/foobar.jpeg'.match(regex) #=> foobar
Can it be done with one regex?
update
Non-regex solutions to this more than welcome!
Upvotes: 1
Views: 72
Reputation:
Not sure of the constraints, but maybe one of these
The dot is problematic in your description if it can be part of like file.name.ext
Otherwise,
Gets the filename in capture group 1 -
# ([^/.]+)(?:\.[^/.]*|/)?\s*$
( [^/.]+ ) # (1)
(?:
\. [^/.]*
| /
)?
\s*
$
This uses lookahead, the match is the filename -
# [^/.]+(?=(?:\.[^/.]*|/)?\s*$)
[^/.]+
(?=
(?:
\. [^/.]*
| /
)?
\s*
$
)
Perl test case
my @ary = (
'baz/foobaryfobar/',
'baz/foobar',
'baz/foobar.jpg',
'baz/foobar.png',
'baz/foobar.gif',
'baz/foobar.jpeg'
);
for $url ( @ary )
{
if ( $url =~ /[^\/.]+(?=(?:\.[^\/.]*|\/)?\s*$)/ ) {
print "matched: $&\n";
}
}
Output >>
matched: foobaryfobar
matched: foobar
matched: foobar
matched: foobar
matched: foobar
matched: foobar
Upvotes: 0
Reputation: 118261
How about without Regex, but using extname
, basename
?
def gen_file_name(string)
File.basename(string,File.extname(string))
end
gen_file_name('baz/foobar.jpg') # => "foobar"
gen_file_name("baz/foobaryfobar/") # => "foobaryfobar"
gen_file_name('baz/foobar') # => "foobar"
Upvotes: 3