Reputation: 175
I have a variable like this below:
G12345(@@)
How can I keep in the variable only the numbers 12345. I have done it before in PHP but I cannot find a way in Perl.
Upvotes: 4
Views: 8878
Reputation: 29854
You can also do it this way:
my ( $number ) = $string =~ /(\d+)/;
This means that were there some other digits to occur after the '(@@)' --for whatever reason, that you would not suddenly concatenate those digits to the number that lies between 'G' and '('. So the capture method makes sure you get the first set of contiguous digits.
Upvotes: 1
Reputation: 62037
This can also be done without regular expressions: Transliterate: tr///
use warnings;
use strict;
my $s = 'G12345(@@)';
$s =~ tr/0-9//cd;
print "$s\n";
__END__
12345
Upvotes: 5
Reputation: 172
Substitute any non-numeric characters with an empty string (\D is non-numeric):
$var =~ s/\D+//g;
Upvotes: 1
Reputation: 943569
$v =~ s/\D//g;
should do the trick.
(Regular expression substitute "Not a number" with "nothing", globally)
Upvotes: 7