I need a regular expression开发者_如何学JAVA to parse a text The directory is /home/foo/bar/hello.txt. I would like to get the hello.txt and get rid of the rest of the directory, so i would like to delete home/foo/bar/ and only get the hello.txt
If you need to do things like that it means that you're using a wrong approach to construct your URIs. You don't need to parse things you construct, you need to have a schema for your URIs.
Update: For files in a filesystem, use File::Basename
update: should work for paths as well :-)
my ($filename) = $dir =~ m!^.*/(.*)!;
or
my $filename = (split '/', $dir)[-1];
I suggest the following equivalent regexes :
my ($extract1) = m { ( [^/]* ) $ }x ;
and with comments added
my ($extract2) = m {
( # start capturing
[^/] * # anything other than / repeated
) # start capturing
$ # anchor to end of string
}x ;
if you add the x at the end then you can add white space and comments to help explain the regex.
精彩评论