开发者

Is there a regular expression to remove a trailing slash in Perl?

I would like开发者_StackOverflow to remove a trailing slash from a string. For example if i have a string called $test = "test/". How would I remove the slash at the end?


With a regular expression do: $test =~ s/\/$//

Alternatively, if you're sure the last character is going to be a slash, you can use the chop function: chop $test


If you are sure that there is one / at the end all the time you can use the chop function:

$test = "test/";
$test = chop($test);

If you are not sure you can do:

$test = "test/";
$test = $1 if($test=~/(.*)\/$/);


Personally I would rephrase this to avoid the mixture of "\" and "/"

$test =~ s|/$||

If you use "|" you don't need to quote the "/"


You can use the s/// substitution operator:

$test =~ s{/\z}{};


This snippet will take care of trailing slashes, except for the root directory:

#!/usr/bin/perl

my $test = './';
$test =~ s{(.+)/\z}{\1};
print $test."\n";

Here is how it works:

The first part of the regular expression - s{(.+)/\z} - defines a group in the brackets (). This is referenced by the \1 in the second part of the regular expression - {\1}. Within this group, I defined one or more characters - .+ - followed immediately by a forward slash, followed by the absolute end of the string - \z.

The regular expression saves everything within the brackets, to be later used as \1 in the replacement specification (the second part, basically.)

This works very similar to a typical sed strategy, viz:

echo "./" | sed -e 's:\(..*\)/$:\1:'

I hope this is of help to you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜