On Thu, 14 Jun 2007, Xavier Noria wrote:
On Jun 14, 2007, at 12:10 PM, Martin Barth wrote:
On Thu, 14 Jun 2007 11:04:51 +0100 (WEST)
Jorge Almeida <[EMAIL PROTECTED]> wrote:
> I'm missing something about Perl's regexp:
>
> 1 #!/usr/bin/perl -w
> 2 use strict;
> 3 my $s=<STDIN>;
> 4 $s=~s/\D*//;
> 5 $s=~s/\D*//;
> 6 print "$s\n";
>
> When input is 'a123b', I get '123b', but I expected '123'. I know I
> can substitute line 4 by '$s=~s/\D*//g;' and comment out line 5. It will
> work then, but that is not the point. I could also substitute line 5 by
> '$s=~s/\D+//;' and it would also work...
>
the problem is * in your regex. i guess the \D* matches on zero non
digits before "123". so nothing will be done.
Not really.
Although + is more concise because you want to delete non-empty sequences of
non-digits and do not care about empty sequences, * will go ahead as much as
possible and would work fine. Jorge was just missing /g.
Xavier,
Martin was right (and I should have seen it from the start). The "will
go ahead as much as possible" is true only in the sense that the
greatest possible string of non-digits will be selected for deletion.
With '$s=~s/\D*//;' in line 5 that string will be empty. In order to
delete the trailing string, the '/g' is needed (but I knew that, as I
said in the original post).
Cheers,
Jorge
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/