开发者

Need help creating a simple regex in Perl

I'm still useless when it comes to creating regex patterns. This one has got to be really easy.

Given the string: /home/users/cheeseconqueso/perl.pl

I want to place the string ./ right in front of the very last / in the original string to produce: /home/users开发者_开发问答/cheeseconqueso/./perl.pl

Thanks in advance - I'm sure this simple example will help me for a lot of other stupid stuff that shouldn't be up here!


Here's my solution based on what I was thinking of when I left the comment to your question:

use strict;
use warnings;

my $str = '/home/users/cheeseconqueso/perl.pl';
my @arr = split('/',$str);
my $newstr = join('/', @arr[0..(@arr-2)], '.', $arr[-1]);

Edit: If you're really keen on using a regex, this is the simplest one I've found:

$str =~ s|(.*/)(.*)|$1./$2|;

It takes advantage of the greediness of the initial * in the first group to take every character up to the last /, then matches everything else in the second group. It's a little easier to read with the | delimiters so you avoid leaning toothpick syndrome.


my $variable = "/home/users/cheeseconqueso/perl.pl";

$variable =~ s/(.*\/)([^\/]+)$/$1\.\/$2/;


this is using File::Basename not with regex, you can use this cpan module if you find hard to write regex.

use File::Basename;
$path = '/home/users/cheeseconqueso/perl.pl';
$newpath = dirname($path) . './'.basename($path);


You actually don't need a regex, you can just split the string:

my $str='/home/users/cheeseconqueso/perl.pl';

#Array: ('','home','users','cheeseconqueso','perl.pl')
my @arr=split(/\//,$str); 

my $output=join('/',@arr[0..($#arr-2)]); # '/home/users/cheeseconqueso'
$output.='/./' . $arr[$#arr]; #Pops on the '/./' and the last element of @arr.


s/(.*)\/(.*)/\1.\/\2/

As noted by CanSpice, split works fine here too.


Try this:

my $str = "/home/users/cheeseconqueso/perl.pl";
if($str =~ /^(.*)(\/)(\w+\.\w+)$/) {
    $str = $1.'/.'.$2.$3;
}


Regex? We don't need no stinkin' regex.

l-value substr() to the rescue!

#!/usr/bin/perl
use warnings;
use strict;

$_ = "/home/users/cheeseconqueso/perl.pl\n";
substr($_, rindex($_, '/'), 0) = '/.';
print;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜