Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

regex help

by rsiedl (Friar)
on Jun 01, 2007 at 04:07 UTC ( [id://618633]=perlquestion: print w/replies, xml ) Need Help??

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

hi monks,

can anyone help me out with this regex? i'm trying to create an array of values that are in a string.
i.e. the string "\"foo\"[MH] or \"bar\"[MH]" should return an array that looks like [ "foo", "bar" ].
here's what i have but it's being greedy:
#!/usr/bin/perl use strict; my $term = "\"foo\"[MH] OR \"bar\"[MH]"; my @matches = ( $term =~ /\"(.+)?\"\[MH\]/ ); print $_,"\n" foreach (@matches);
any help would be appreciated.

cheers,
reagen

Replies are listed 'Best First'.
Re: regex help
by kyle (Abbot) on Jun 01, 2007 at 04:17 UTC

    Two small changes will help. The new regex line is:

    my @matches = ( $term =~ /\"(.*?)\"\[MH\]/g );

    The first change is to make the capture non-greedy (from (.+)? to (.*?)). The second change is to use the /g flag to collect all the matches, not just the first one. Have a look at perlre for all the gory details.

Re: regex help
by sanPerl (Friar) on Jun 01, 2007 at 05:11 UTC
    (.+)? and (.+) works same in your case, because (.+) forms a greedy pattern first and which nullifies the presence of ?
Re: regex help
by Samy_rio (Vicar) on Jun 01, 2007 at 04:17 UTC

    Hi, Try now,

    #!/usr/bin/perl use strict; my $term = "\"foo\"[MH] OR \"bar\"[MH]"; my @matches = $term =~ /(\"(.+)?\"\[MH\])/ ; print $_,"\n" foreach (@matches);

    Regards,
    Velusamy R.


    eval"print uc\"\\c$_\""for split'','j)@,/6%@0%2,`e@3!-9v2)/@|6%,53!-9@2~j';

      Your code produces the same output as the OP's code. You didn't fix anything.
Re: regex help
by blazar (Canon) on Jun 01, 2007 at 15:11 UTC
    my $term = "\"foo\"[MH] OR \"bar\"[MH]"; my @matches = ( $term =~ /\"(.+)?\"\[MH\]/ );

    As a side note you don't have to do double-quotes-quoting-acrobatics: just use single quotes or alternate delimiters (should you need interpolation or "\*" thingies).

    my $term = '"foo"[MH] OR "bar"[MH]';

    or

    my $term = qq|"foo"[MH] OR "bar"[MH]|;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-20 01:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found