Perl Regular Expressions: Question mark isn't greedily matching
$var = 'about/';
$var =~ s/^(.*)\/?$/index.php?action=$1/;
I want it to match and substitute the trailing slash. But it isn't, I'm getting this result:
index.php?action=about/
What am I doing wrong? I've tried wrapping it in parenthesis (\/)?
and including the question mark in the parenthesis (\/?)
. Not including the preceding fo开发者_如何学编程rward slash obviously doesn't do me any good. So how can I get it to eat the slash when it's there?
Your problem is, that the .*
is greedy as well. Try using .*?
.
The Regex engine is first expanding .*
as far as possible, then checks if the regex can match the input. In your case, it does, since the trailing slash is optional. It then goes home satisfied.
Make .*
ungreedy :
$var = 'about/';
$var =~ s!^(.*?)/?$!index.php?action=$1!;
In your substitution, you're trying really hard to specify what you keep. It's much easier in this case to get rid of what you don't want. When a feature seems hard to use for your application, that's a sign that you're using the wrong feature.
It looks like you want to do is remove the last / in a string. So, just remove the last /:
my $path = 'about/';
$path = s|/\z||;
my $action = "index.php?action=$path";
If you really wanted to do this in-place (a dubious goal), you could just do this:
( my $action = "index.php?action=$path" ) =~ s|/\z||;
精彩评论