(.*) function

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

(.*) function

Smruti Mohanty
#!usr/bin/perl
use warnings;
use strict;


my $x = 'Ram 10 abc xyz abc 5';

if ($x =~m/([a-zA-Z]+) (.*) (\d)/){
        print "$1 \n";
        print "$2 \n";
        print "$3";
}

.* is supposed to be greedy then why the program is having such output?
$1 -> Ram
$2 -> 10 abc xyz
$3 -> 5

And following program is not yielding any output also...Why?

my $x = 'Ram 10 abc xyz abc 5';

if ($x =~m/([a-zA-Z]+)\s+ (.*?) \s+ (\d)/){
        print "$1 \n";
        print "$2 \n";
        print "$3";
}
Reply | Threaded
Open this post in threaded view
|

Re: (.*) function

Guru
Administrator
.* is indeed greedy, and the output of the first code snippet shows exactly that. When the regex "(.*) (\d)" is provided, .* matches everything from "abc" till the end of the string. However, on realising that you are trying to match a space and a single digit, it starts giving up characters from the end, and hence the \d ends up matching the number 5.

Hope this helps. If not clear, please tell what output you expected in this scenario so that we will try to change the regex.
Reply | Threaded
Open this post in threaded view
|

Re: (.*) function

Smruti Mohanty
And following program is not yielding any output ...Why?

my $x = 'Ram 10 abc xyz abc 5';

if ($x =~m/([a-zA-Z]+)\s+ (.*?) \s+ (\d)/){
        print "$1 \n";
        print "$2 \n";
        print "$3";
}


Reply | Threaded
Open this post in threaded view
|

Re: (.*) function

Guru
Administrator
This is not yielding any output because the regex does not match anything and hence it fails as a result it does not get into the if block:

([a-zA-Z]+)\s+  => Matches Ram followed by one or more spaces

Followed by the "\s+", immediately there is a space " " which will never get matched because \s+ itself has matched the available spaces.  And the same thing is repeated afterwards, same thing meaning \s followed by a space.