"perl regular expressions are greedy" what does this mean?

Showing Answers 1 - 4 of 4 Answers

Manjusha1

  • May 17th, 2006
 

Perl regular expressions normally match the longest string possible. that is what is called as "greedy match" For instance:my($text) = "mississippi";$text =~ m/(i.*s)/;print $1 . "\n";Run the preceding code, and here's what you get:ississIt matches the first i, the last s, and everything in between them. But what if you want to match the first i to the s most closely following it? Use this code:my($text) = "mississippi";$text =~ m/(i.*?s)/;print $1 . "\n";Now look what the code produces:is

  Was this answer useful?  Yes

a@a.com

  • May 18th, 2006
 

Perl regular expressions normally match the longest string possible. For instance:

my($text) = "mississippi";
$text =~ m/(i.*s)/;
print $1 . "\n";
Run the preceding code, and here's what you get:
ississ

  Was this answer useful?  Yes

prabhath_01

  • May 31st, 2008
 

We have wild card characters like '*' and '+' in perl, which are greedy by nature
Eg:., Let's discuss with an example  
In the following string you want to match 'Perl is awesome'.

my $str = "Perl is awesome, I am also awesome";
$str =~ /.*awesome/;
print $&,"n";


At this point you were expecting the output as 'Perl is awesome'.But you will be stunned if you see the output.Don't worry at all, be cooool.
Be brave to see the output.

o/p: Perl is awesome, I am also awesome

'*' is always greedy, it wont' be satisfied with the first match itself.It is greedy, so it ill match uoto the last occurance of the match.

So how you restrict the greedyness, like stop matching as soon as the first match.There is answer for this also.
my $str = "Perl is awesome, I am also awesome";
$str =~ /.*?awesome/;  #We used '?'
print $&,"n";

Use '?' after greedy operator '*' or '+'.
o/p: Perl is awesome.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions