Home > Archive > PERL Beginners > October 2005 > finding the first non digit character in a string
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
finding the first non digit character in a string
|
|
| Bruce Bowen 2005-10-28, 6:56 pm |
| I see where you can test for a match in a string of data using the If ( )
statement, but can you use it with an 'index' statement?
The data may look like this:
$DD = "5000|SIHHTEXT"
I've tried $d = index($DD, m/[^\d]/);
$d = index($DD, /[^\d]/);
$d = index($DD, [^\d]);
none of which worked.
While the text sting will always start out with some numbers, (a dollar
amount without the dollar sign) I can't always tell how large the amount
will be or if there will be any cents. I need to extract the dollar / cents
out from the text. Any suggestions as to how that can be done?
Thanks,
Bruce Bowen
401-568-8315
| |
| Adriano Ferreira 2005-10-28, 6:56 pm |
| On 10/28/05, Bowen, Bruce <Bowenb@diebold.com> wrote:
> The data may look like this:
> $DD =3D "5000|SIHHTEXT"
> I've tried $d =3D index($DD, m/[^\d]/);
> $d =3D index($DD, /[^\d]/);
> $d =3D index($DD, [^\d]);
C<index> doesn't work with regexes. But you can use C<pos>
$ perl -e '$DD =3D "5000|SIHHTEXT"; print pos($DD) if $DD =3D~ /\D/g'
5
Read about this usage at C<perldoc -f pos>.
Adriano.
| |
| Jeff 'japhy' Pinyan 2005-10-28, 6:56 pm |
| On Oct 28, Bowen, Bruce said:
> I see where you can test for a match in a string of data using the If ( )
> statement, but can you use it with an 'index' statement?
The index() function is for finding a string in another string. Patterns
(regexes) are not allowed.
> $DD = "5000|SIHHTEXT"
>
> I've tried $d = index($DD, m/[^\d]/);
> $d = index($DD, /[^\d]/);
> $d = index($DD, [^\d]);
You want the location of the first non-digit?
my $non_digit = ($DD =~ /\D/) ? $-[0] : -1; # -1 means not found
(See 'perlvar' for an explanation of $-[0], in the @- array.)
> will be or if there will be any cents. I need to extract the dollar / cents
> out from the text. Any suggestions as to how that can be done?
That's much simpler:
my ($money) = $DD =~ /^(\d+\.?\d*)/;
That will match the numbers at the beginning of the string, optionally
allowing for a decimal point (\.) and digits after it.
--
Jeff "japhy" Pinyan % How can we ever be the sold short or
RPI Acacia Brother #734 % the cheated, we who for every service
http://www.perlmonks.org/ % have long ago been overpaid?
http://princeton.pm.org/ % -- Meister Eckhart
|
|
|
|
|