开发者

Regular Expression to parse a string from end until a delimiter is reached(Perl)

开发者 https://www.devze.com 2022-12-24 15:59 出处:网络
I need a regular expression开发者_如何学JAVA to parse a textThe directory is /home/foo/bar/hello.txt.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号