Michael Alipio wrote:
Hi,
Hello,
Subject: Turn off $ anchor greedy behavior
Anchors are not greedy. Anchors don't even match characters.
I have a $string that is separated by , and space;
boy, pig, 123, 123:412adbd, d0g, lajdlf134><<_ lkadsf !234,
Now I want to capture the string(s) between last two commas. It
consists of anything upto 32 characters. that is, right after d0g,\s+
up to the last character before the last comma at the end of the line.
if I do something like
(my $value) = $_ ~= /,\s+(.*),\s+$/;
The modifier * is greedy, but that is not your problem. Matches start
searching at the left so ',\s+' will match the first comma-whitespace
and then '(.*)' will match everthing except newline to the last ',\s+'
comma-whitespace. The anchor is superfluous because '.*' is greedy.
$value would start matching from "pig" because when I used $ and it
looked back, the first thing it would match is ", pig.... upto the end
of the line"
I wonder how you could match only the pattern which is nearest to the
end of the line having used $ anchor.
To get around this, I could split the lines push each comma delimited
string into an array and finally print the last element which is a lot
of work to do.
Is there some sort of turning of greedy behavior of the $ anchor?
You could put a greedy match in front of your pattern:
$ perl -le'
my $string = "boy, pig, 123, 123:412adbd, d0g, lajdlf134><<_ lkadsf
!234,\n";
my ( $value ) = $string =~ /.*,\s+(.*),\s+/;
print $value;
'
lajdlf134><<_ lkadsf !234
Or use split and return the last field:
$ perl -le'
my $string = "boy, pig, 123, 123:412adbd, d0g, lajdlf134><<_ lkadsf
!234,\n";
my $value = ( split /,\s+/, $string )[ -1 ];
print $value;
'
lajdlf134><<_ lkadsf !234
John
--
Those people who think they know everything are a great
annoyance to those of us who do. -- Isaac Asimov
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/