Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

pattern matching

by Anonymous Monk
on Aug 21, 2002 at 11:28 UTC ( [id://191694]=perlquestion: print w/replies, xml ) Need Help??

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

Hello perlmonks!:) I would be really happy if anyone could help me with my "problem"... I want to search an array, and return alle id's and p_id's. An example of an array element: (:ID 10000000 :USERNAME "xxxxxxx" :P_ID 12000000 :+++++++++) Thanx! :)

Replies are listed 'Best First'.
Re: pattern matching
by Tanalis (Curate) on Aug 21, 2002 at 11:39 UTC
    A simple pattern match to return 10000000 for the ID and 12000000 for the P_ID would be:

    /:ID\s(\d*).*:P_ID\s(\d*)/

    You can then refer to the matches using $1 and $2 respectively.

    Hope this helps.
    -- Foxcub

      Thanx again!:) Does the snippet work if there are more than one ID/P_ID in an array element?
        If you want to act on more than one id then try
        while ($arrayElement =~ /:ID\s(\d*).*:P_ID\s(\d*)/g ) { print $1,$2,"\n"; # just an example }
        The /g gets all matches of the regex, so the captured bit ($1,$2) will be updated for each match in the while loop.
        For that, you'd want to use the global (/g) modifier on the end of your regex, and use the regex in a list context:
        @ids = m/:ID\s\d*/g

        You'll need to do another regex to pull the P_IDs,
        @p_ids = m/:P_ID\s\d*/g,
        and you won't be able to use backreferencing to ditch the ":ID " part.

        For that, I guess you could use another regex, or, if the data is regular, something like:
        for $i (0..$#ids) {$ids[Ģi] = substr ($ids[$i], 4);}

        No, you'll have to think a little here.

        Hotshot
Re: pattern matching
by thor (Priest) on Aug 21, 2002 at 12:15 UTC
    as for me, I'd use a little split action, as it looks like you are using colon-separated records. This has the advantage of isolating the fields from each other, allowing you to more easily (and safely) extract their content.
    while(<>){ my ($id, $user_name, $p_id, $password) = split ':'; #do stuff to the stuff in $id and $p_id }

    thor

Re: pattern matching
by hotshot (Prior) on Aug 21, 2002 at 11:58 UTC

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2024-03-29 15:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found