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

If I search a file using
while ($str=~ /(DPL.|RVL.|[IV]LK.|FVK.)/g)
will it search for all the patterns, or will it only search for DPL. if that's what it finds first? I need it to find all strings matching all these patterns somehow!

edited: 17 Jun 2002 by jeffa - added code tags

Replies are listed 'Best First'.
Re: use of 'or' in regex
by RMGir (Prior) on Jun 17, 2002 at 13:23 UTC
    (Use the <code> tag to delimit code blocks like your regex, or PM will interpret them as square-bracket special link codes...)

    In this case, perl will return the list of those patterns that match. So you're ok, since your patterns don't overlap.

    If you had something like this:

    $str=~/(DPL|DPLA)/g
    then the DPLA alternative would never match, since DPL would.

    Edit: Someone said in /msg that I'm wrong if the string is "DPLA DPL", claiming both will match.

    However, in that case, _DPL_ is what matches twice; DPLA never matches.

    $ perl -ne'while(/(DPL|DPLA)/g){print " > $1 <\n"}' DPL > DPL < DPLA > DPL < DPLA DPL > DPL < > DPL < DPLA DPLA > DPL < > DPL <
    If I had specified DPLA|DPL, then the match would have been as expected.
    --
    Mike
Re: use of 'or' in regex
by marvell (Pilgrim) on Jun 17, 2002 at 13:26 UTC
    You may be interested to know that the output of:
    $str = "ABCDEFGHIJKLM"; while ($str =~ /(BC|GH|LM)/g) { print "matched $1\n"; }
    is:
    matched BC matched GH matched LM
    Which I think is what you needed. You'll get a match line for each of them, so long as they don't overlap.

    --
    Steve Marvell

Re: use of 'or' in regex
by mrbbking (Hermit) on Jun 17, 2002 at 15:05 UTC
    Why not use your regex to ask the same question of Perl itself?
    #!/usr/bin/perl -w use strict; my $str = 'DPL1 DPLx RVLj ILKy VLKy Bartleby the ScriFVKner'; while ($str=~ /(DPL.|RVL.|[IV]LK.|FVK.)/g){ print "matched '$1' in string '$str'\n"; }