Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

String Matching

by mattwortho (Acolyte)
on Sep 18, 2007 at 11:18 UTC ( [id://639614]=perlquestion: print w/replies, xml ) Need Help??

mattwortho has asked for the wisdom of the Perl Monks concerning the following question:

Hello all, I was wondering if I could please get some help on the following problem. I need to get a list of numbers out of strings but I don't know how many numbers are in each string. The strings are as follows:
my $line1 = "[HAVE 1324,2,32,324,5,643] my $line2 = "[HAVE 4,213,5432,4]
I would ideally like to parse each line and have all the numbers of a single line in an array, say
my @numbers =();
After reading the first line, it should contain (1324,2,32,324,5,643) and after reading the second line it should contain (4,213,5432,4). Not sure how to match strings when the format isn't constant. Thanks in advance for your help, Matt.

Replies are listed 'Best First'.
Re: String Matching
by Anno (Deacon) on Sep 18, 2007 at 11:32 UTC
    You only have to globally match each sequence of consecutive digits. A global match (in list context) returns all its matches, so this would do
    my $line1 = "[HAVE 1324,2,32,324,5,643]"; my $line2 = "[HAVE 4,213,5432,4]"; for ( $line1, $line2 ) { my @numbers = /\d+/g; print "@numbers\n"; }
    Anno
Re: String Matching
by bruceb3 (Pilgrim) on Sep 18, 2007 at 11:38 UTC
    There are a number of ways of going about providing a solution to your problem. I have gone for a simple regex;
    #!/usr/bin/env perl use strict; use warnings; use Data::Dumper; my @lines = ( "[HAVE 1324,2,32,324,5,643]", "[HAVE 4,213,5432,4]"); for my $line (@lines) { my @numbers; while ($line =~ /(\d+)/g) { push @numbers, $1; } print Dumper \@numbers; }
    Produces the following output;
    $VAR1 = [ '1324', '2', '32', '324', '5', '643' ]; $VAR1 = [ '4', '213', '5432', '4' ];

    You could use s/// to remove the extra characters and use split on the commas if you like.

Re: String Matching
by mattwortho (Acolyte) on Sep 18, 2007 at 11:32 UTC
    I was thinking maybe something along these lines...
    if($line2 =~ /[HAVE\s(.*)]/){ my @array = split(/,/, $2); foreach my $num(@array){ print $num."\n"; } }
    Not sure if this is the best way....
Re: String Matching
by ciderpunx (Vicar) on Sep 18, 2007 at 12:11 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://639614]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2024-04-25 09:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found