tags:

views:

87

answers:

3
$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 forward slash obviously doesn't do me any good. So how can I get it to eat the slash when it's there?

+9  A: 

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.

Jens
Oh, of course. *sigh* RegEx's have always given me trouble, because there's always something like that that manages to bite me in the butt. Thanks!
Daniel Bingham
The trick is to not use more regex than you really need. :)
brian d foy
+5  A: 

Make .* ungreedy :

$var = 'about/';
$var =~ s!^(.*?)/?$!index.php?action=$1!;
M42
A: 

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||; 
brian d foy
Not quite what I was trying to do. This is a regex that is eventually going to find its way into a MOD_REWRITE RewriteRule. And this is only part of the final result. I'm just testing it in bits an pieces in Perl and putting it together so that I know it'll do what I want when I finally put it into an htaccess file.
Daniel Bingham
That would have been good information to include in your question. It's always a little sad when I find out I've wasted my time because the questioner left out really important information like that.
brian d foy