Perl regular expressions: the question mark is not a greedy combination

$var = 'about/';
$var =~ s/^(.*)\/?$/index.php?action=$1/;

I want it to match and replace the trailing slash. But this is not so, I get this result:

index.php?action=about/

What am I doing wrong? I tried wrapping it in brackets (\/)?and including a question mark in a parenthesis (\/?). Apart from the previous slash, I'm obviously not doing any good. So how can I get him to have a slash when she is there?

+3
source share
3 answers

Your problem is .*also greedy. Try to use .*?.

Regex .*, , , . , . .

+11

.* ungreedy:

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

, . , . , , .

, / . , /:

 my $path = 'about/';
 $path = s|/\z||;

 my $action = "index.php?action=$path";

( ), :

 ( my $action = "index.php?action=$path" ) =~ s|/\z||; 
0

Source: https://habr.com/ru/post/1766166/


All Articles