问题描述:

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;
相关阅读:
Top