Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

pattern match of first occurance

by Selvakumar (Scribe)
on Jul 08, 2010 at 10:11 UTC ( [id://848662]=perlquestion: print w/replies, xml ) Need Help??

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

Hi All,
I want to find the first occurance of pattern matching for "year". How can i do that?

$var='<x><year>2010<day>5</day></year><month>January</month> <day>31</ +day>, <year>2010</year></x>'; $var=~/<year>(.+)<\/year>/; print $1;

from the above coding i am getting the result
2010<day>5</day></year><month>January</month> <day>31</day>, <year>2010 but i need the below output.
2010<day>5</day>

Replies are listed 'Best First'.
Re: pattern match of first occurance
by johngg (Canon) on Jul 08, 2010 at 10:41 UTC

    Your match (.+) is greedy so it will match as much as possible, i.e. up to the second </year>. Make it non-greedy with the addition of a question mark.

    $ perl -E ' > $var = q{<x><year>2010<day>5</day></year><month>January</month> <day +>31</day>, <year>2010</year></x>}; > say $1 if $var =~m{<year>(.+?)</year>};' 2010<day>5</day> $

    I hope this is helpful.

    Cheers,

    JohnGG

      Or match only digits:
      say $1 if $var =~m{<year>(\d+)</year>};

      rdfield

        Comment: Nope he said he's trying to get:
        2010<day>5</day>



        Demize
Re: pattern match of first occurance
by Anonymous Monk on Jul 08, 2010 at 10:36 UTC
    Use a parser
    $var='<x><year>2010<day>5</day></year><month>January</month> <day>31</ +day>, <year>2010</year></x>'; use Data::Dumper; use XML::Simple; die Dumper( XMLin( $var ) ); __END__ $VAR1 = { 'month' => 'January', 'content' => ', ', 'day' => '31', 'year' => [ { 'day' => '5', 'content' => '2010' }, '2010' ] };

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-26 01:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found